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 program to test above function
function nextGreatest ( arr , size ) { max_from_right = arr [ size - 1 ] ; arr [ size - 1 ] = - 1 ; for ( let 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 ) { var i ; for ( let i = 0 ; i < size ; i ++ ) document . write ( arr [ i ] + " " ) ; } arr = new Array ( 16 , 17 , 4 , 3 , 5 , 2 ) ; size = arr . length ; nextGreatest ( arr , size ) ; document . write ( " " + " " + " " ) ; printArray ( arr , size ) ;