Previous greater element | Javascript 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
function prevGreater ( arr , n ) { document . write ( " " ) ; for ( let i = 1 ; i < n ; i ++ ) { let j ; for ( j = i - 1 ; j >= 0 ; j -- ) { if ( arr [ i ] < arr [ j ] ) { document . write ( arr [ j ] + " " ) ; break ; } } if ( j == - 1 ) document . write ( " " ) ; } } let arr = [ 10 , 4 , 2 , 20 , 40 , 12 , 30 ] ; let n = arr . length ; prevGreater ( arr , n ) ;