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 ; Array size ; 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 ; Print the final array ; Given array ; Function call
function printFinalPrices ( arr ) { var minStk = [ ] var n = arr . length ; var i ; var reduce = Array ( n ) . fill ( 0 ) ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( minStk . length > 0 ) { if ( minStk [ minStk . length - 1 ] <= arr [ i ] ) { reduce [ i ] = minStk [ minStk . length - 1 ] ; } else { while ( minStk . length > 0 && ( minStk [ minStk . length - 1 ] > arr [ i ] ) ) { minStk . pop ( ) ; } if ( minStk . length > 0 ) { reduce [ i ] = minStk [ minStk . length - 1 ] ; } } } minStk . push ( arr [ i ] ) ; } for ( i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] - reduce [ i ] + " " ) ; } var arr = [ 8 , 4 , 6 , 2 , 3 ] ; printFinalPrices ( arr ) ;