From 075ef633046bf49d984940941caee7c54c933268 Mon Sep 17 00:00:00 2001 From: Harshit Sharma <55287441+harshit-3103@users.noreply.github.com> Date: Thu, 6 Oct 2022 00:45:12 +0530 Subject: [PATCH] NearestGreaterElementFromRight Find the Nearest Greater Element From Right Side in the given array. If in the right side no greater element then print -1. --- 2.stacks/NearestGreaterElementFromRight.cpp | 53 +++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 2.stacks/NearestGreaterElementFromRight.cpp diff --git a/2.stacks/NearestGreaterElementFromRight.cpp b/2.stacks/NearestGreaterElementFromRight.cpp new file mode 100644 index 000000000..76369da63 --- /dev/null +++ b/2.stacks/NearestGreaterElementFromRight.cpp @@ -0,0 +1,53 @@ +#include +using namespace std; + +// Next Greater Right Element +vector solve(vector a) +{ + // output vector + vector ans; + + stack s; + int n = a.size(); + // from back side + for(int i=n-1;i>=0;i--){ + // base case + if(s.size()==0){ + ans.push_back(-1); + } + else if(s.size()>0 && a[i]0 && a[i]>=s.top()){ + while(s.size()>0 && a[i]>=s.top()){ + s.pop(); + } + if(s.size()==0){ + ans.push_back(-1); + } + else{ + ans.push_back(s.top()); + } + } + s.push(a[i]); + } + // reverse the array bcz element store from back side + reverse(ans.begin(),ans.end()); + + return ans; +} + +int main(){ + int n; + cin>>n; + vector v(n); + for(int i=0;i>v[i]; + } + // print the output + vector ans = solve(v); + for(int i=0;i