diff --git a/cpp/Next_Greater_Element.cpp b/cpp/Next_Greater_Element.cpp new file mode 100644 index 0000000..b03a7bf --- /dev/null +++ b/cpp/Next_Greater_Element.cpp @@ -0,0 +1,60 @@ +/*Problem Statement - Given an array, print the Next Greater Element (NGE) for every element. +The Next greater Element for an element x is the first greater element on the right side of x in the array. +Elements for which no greater element exist, consider the next greater element as -1. */ + +//Problem Link - https://www.geeksforgeeks.org/next-greater-element/ + +#include +using namespace std; +vector nextLargerElement(vector arr, int n) +{ + + vector ans(n); + stack st; + st.push(n-1); + ans[n-1]=-1; + + for(int i=n-2; i>=0; i--) + { + if(st.empty()) + { + ans[i] = -1; + st.push(i); + } + else + { + while(!st.empty() && arr[st.top()]>n; + + vector arr(n); + for(int i=0; i>arr[i]; + } + + vector ans = nextLargerElement(arr, n); + for(int i=0; i