Replace every element with the greatest element on right side | Function to replace every element with the next greatest element ; Initialize the next greatest element ; The next greatest element for the rightmost element is always - 1 ; Replace all other elements with the next greatest ; Store the current element ( needed later for updating the next greatest element ) ; Replace current element with the next greatest ; Update the greatest element , if needed ; A utility Function that prints an array ; Driver Code
< ? php function nextGreatest ( & $ arr , $ size ) { $ max_from_right = $ arr [ $ size - 1 ] ; $ arr [ $ size - 1 ] = -1 ; for ( $ i = $ size - 2 ; $ i >= 0 ; $ i -- ) { $ temp = $ arr [ $ i ] ; $ arr [ $ i ] = $ max_from_right ; if ( $ max_from_right < $ temp ) $ max_from_right = $ temp ; } } function printArray ( $ arr , $ size ) { for ( $ i = 0 ; $ i < $ size ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; echo " STRNEWLINE " ; } $ arr = array ( 16 , 17 , 4 , 3 , 5 , 2 ) ; $ size = count ( $ arr ) ; nextGreatest ( $ arr , $ size ) ; echo " The ▁ modified ▁ array ▁ is : ▁ STRNEWLINE " ; printArray ( $ arr , $ size ) ; ? >