Previous greater element | C ++ program previous greater element A naive solution to print previous greater element for every element in an array . ; Previous greater for first element never exists , so we print - 1. ; Let us process remaining elements . ; Find first element on left side that is greater than arr [ i ] . ; If all elements on left are smaller . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void prevGreater ( int arr [ ] , int n ) { cout << " - 1 , ▁ " ; for ( int i = 1 ; i < n ; i ++ ) { int j ; for ( j = i - 1 ; j >= 0 ; j -- ) { if ( arr [ i ] < arr [ j ] ) { cout << arr [ j ] << " , ▁ " ; break ; } } if ( j == -1 ) cout << " - 1 , ▁ " ; } } int main ( ) { int arr [ ] = { 10 , 4 , 2 , 20 , 40 , 12 , 30 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; prevGreater ( arr , n ) ; return 0 ; }