Previous greater element | C ++ program previous greater element An efficient solution to print previous greater element for every element in an array . ; Create a stack and push index of first element to it ; Previous greater for first element is always - 1. ; Traverse remaining elements ; Pop elements from stack while stack is not empty and top of stack is smaller than arr [ i ] . We always have elements in decreasing order in a stack . ; If stack becomes empty , then no element is greater on left side . Else top of stack is previous greater . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void prevGreater ( int arr [ ] , int n ) { stack < int > s ; s . push ( arr [ 0 ] ) ; cout << " - 1 , ▁ " ; for ( int i = 1 ; i < n ; i ++ ) { while ( s . empty ( ) == false && s . top ( ) < arr [ i ] ) s . pop ( ) ; s . empty ( ) ? cout << " - 1 , ▁ " : cout << s . top ( ) << " , ▁ " ; s . push ( arr [ i ] ) ; } } int main ( ) { int arr [ ] = { 10 , 4 , 2 , 20 , 40 , 12 , 30 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; prevGreater ( arr , n ) ; return 0 ; }