Previous greater element | php 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
< ? php function prevGreater ( & $ arr , $ n ) { echo ( " - 1 , ▁ " ) ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { for ( $ j = $ i - 1 ; $ j >= 0 ; $ j -- ) { if ( $ arr [ $ i ] < $ arr [ $ j ] ) { echo ( $ arr [ $ j ] ) ; echo ( " , ▁ " ) ; break ; } } if ( $ j == -1 ) echo ( " - 1 , ▁ " ) ; } } $ arr = array ( 10 , 4 , 2 , 20 , 40 , 12 , 30 ) ; $ n = sizeof ( $ arr ) ; prevGreater ( $ arr , $ n ) ; ? >