-
Notifications
You must be signed in to change notification settings - Fork 0
/
496. Next Greater Element I
39 lines (39 loc) · 1.62 KB
/
496. Next Greater Element I
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
38
39
//🎯DAY 18 PROBLEM 1
//Apply next greater element problem in nums2 array, there will be three condition, when the array is empty.. When the top of stack is smaller than current element......
//When the top of stack is greater than the element
//1)When stack is empty, i.e. there is no greater element on right, so we insert -1
//2)When the stack's top is greater, we insert stack's top in the answer
//3)But when the stack's top is lesser, then we keep on popping untill stack's top is smaller than current element as we will not need them in further calculations also
//as our current element will serve as the next greater element.
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
stack<int>st;
map<int,int>result;
for(int i=nums2.size()-1;i>=0;i--)
{
if(st.empty())
result.insert({nums2[i],-1});
else if(st.top()>nums2[i])
result.insert({nums2[i],st.top()});
else if(st.size()>0&&st.top()<nums2[i])
{
while(st.size()>0&&st.top()<nums2[i])
{
st.pop();
}
if(st.empty())
result.insert({nums2[i],-1});//if stack's top becomes empty, we push -1
else
result.insert({nums2[i],st.top()});//if stack's top becomes greater, we insert that in the map .
}
st.push(nums2[i]);
}
vector<int>ans;
for(int i=0;i<nums1.size();i++)
{
ans.push_back(result[nums1[i]]);
}
return ans;
}
};