-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDaily Temperatures.cpp
30 lines (25 loc) Β· 1.17 KB
/
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
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int>nge(n, 0); // initially all 0, stores distance between their next greater element and current temperature
stack<int>st{};
// move from right to left
for(int i = n-1; i>=0; --i){
// pop until we find next greater element to the right
// since we came from right stack will have element from right only
// s.top() is the index of elements so we put that index inside temperatures vector to check
while(!st.empty() && temperatures[st.top()] <= temperatures[i])
st.pop();
// if stack not empty, then we have some next greater element,
// so we take distance between next greater and current temperature
// as we are storing indexes in the stack
if(!st.empty())
nge[i] = st.top()-i; // distance between next greater and current
// push the index of current temperature in the stack,
// same as pushing current temperature in stack
st.push(i);
}
return nge;
}
};