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 ; Utility function to print an array ; Driver function to test above function
def nextGreatest ( arr ) : NEW_LINE INDENT size = len ( arr ) NEW_LINE max_from_right = arr [ size - 1 ] NEW_LINE arr [ size - 1 ] = - 1 NEW_LINE for i in range ( size - 2 , - 1 , - 1 ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = max_from_right NEW_LINE if max_from_right < temp : NEW_LINE INDENT max_from_right = temp NEW_LINE DEDENT DEDENT DEDENT def printArray ( arr ) : NEW_LINE INDENT for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT DEDENT arr = [ 16 , 17 , 4 , 3 , 5 , 2 ] NEW_LINE nextGreatest ( arr ) NEW_LINE print " Modified ▁ array ▁ is " NEW_LINE printArray ( arr ) NEW_LINE