Modify given array by reducing each element by its next smaller element | Function to print the final array after reducing each array element by its next smaller element ; Initialize stack ; To store the corresponding element ; If stack is not empty ; If top element is smaller than the current element ; Keep popping until stack is empty or top element is greater than the current element ; If stack is not empty ; Push current element ; Final array ; Driver Code ; Given array ; Function Call
def printFinalPrices ( arr ) : NEW_LINE INDENT minStk = [ ] NEW_LINE reduce = [ 0 ] * len ( arr ) NEW_LINE for i in range ( len ( arr ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if minStk : NEW_LINE INDENT if minStk [ - 1 ] <= arr [ i ] : NEW_LINE INDENT reduce [ i ] = minStk [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT while minStk and minStk [ - 1 ] > arr [ i ] : NEW_LINE INDENT minStk . pop ( ) NEW_LINE DEDENT if minStk : NEW_LINE INDENT reduce [ i ] = minStk [ - 1 ] NEW_LINE DEDENT DEDENT DEDENT minStk . append ( arr [ i ] ) NEW_LINE DEDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] - reduce [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 4 , 6 , 2 , 3 ] NEW_LINE printFinalPrices ( arr ) NEW_LINE DEDENT