forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0739-daily-temperatures.cpp
37 lines (28 loc) · 988 Bytes
/
0739-daily-temperatures.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
Given array of temps, return an array w/ # of days until warmer
Ex. temperature = [73,74,75,71,69,72,76,73] -> [1,1,4,2,1,1,0,0]
Monotonic decr stack, at each day, compare incr from prev days
Time: O(n)
Space: O(n)
*/
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
// pair: [index, temp]
stack<pair<int, int>> stk;
vector<int> result(n);
for (int i = 0; i < n; i++) {
int currDay = i;
int currTemp = temperatures[i];
while (!stk.empty() && stk.top().second < currTemp) {
int prevDay = stk.top().first;
int prevTemp = stk.top().second;
stk.pop();
result[prevDay] = currDay - prevDay;
}
stk.push({currDay, currTemp});
}
return result;
}
};