Skip to content

Commit d557b45

Browse files
Update daily_temperatures.cpp
1 parent 7a3ac25 commit d557b45

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

daily_temperatures.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,43 @@
1+
class Solution {
2+
public:
3+
vector<int> dailyTemperatures(vector<int>& T) {
4+
5+
6+
/*
7+
Next greater to right and difference.
8+
Start scanning from right end of array.
9+
*/
10+
11+
12+
stack<pair<int, int>> S; // S.top()[0] ==> temperature, S.top()[1] ==> next warmer(>) temperature
13+
14+
int n = T.size();
15+
vector<int> result(n, 0);
16+
17+
for(int i=n-1; i>=0; i--) {
18+
19+
//
20+
while(!S.empty() and S.top().first <= T[i]) { //if current element is greater than element at top of stack..pop the element until we find next greater element in stack(next warmer temperature)
21+
S.pop();
22+
}
23+
24+
// once we found it, push the difference between current element to its next warmer temperature in result array.
25+
if(!S.empty() and T[i] < S.top().first) {
26+
result[i] = S.top().second - i;
27+
}
28+
29+
S.push({T[i], i});
30+
}
31+
return result;
32+
33+
}
34+
};
35+
36+
37+
38+
/*
39+
More optimized in terms of time and space.
40+
141
class Solution {
242
public:
343
vector<int> dailyTemperatures(vector<int>& T) {
@@ -14,3 +54,4 @@ class Solution {
1454
return next_greatest;
1555
}
1656
};
57+
*/

0 commit comments

Comments
 (0)