Next Greater Element II
https://leetcode.com/problems/next-greater-element-ii/
vector<int> nextGreaterElements(vector<int>& nums) {
int n=nums.size();//size
vector<int>nqe(n,-1);//vector initialized with -1
stack<int> s;
for(int i=(2*n-1);i>=0;i--){ //to create a circular array and traverse from right to left
while(!s.empty() && s.top()<=nums[i%n]) //if stack empty,(i%n because of circular array logic)
{
s.pop(); // we need to pop
}
if(i<n){
if(!s.empty()){
nqe[i]=s.top();
}
}
s.push(nums[i%n]);
}
return nqe;
}
Comments
Post a Comment