Modify given array by reducing each element by its next smaller element | Java program for the above approach ; 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 ; Driver Code ; Given array ; Function call
import java . util . * ; class GFG { static void printFinalPrices ( int [ ] arr ) { Stack < Integer > minStk = new Stack < > ( ) ; int n = arr . length ; int [ ] reduce = new int [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( ! minStk . isEmpty ( ) ) { if ( minStk . peek ( ) <= arr [ i ] ) { reduce [ i ] = minStk . peek ( ) ; } else { while ( ! minStk . isEmpty ( ) && ( minStk . peek ( ) > arr [ i ] ) ) { minStk . pop ( ) ; } if ( ! minStk . isEmpty ( ) ) { reduce [ i ] = minStk . peek ( ) ; } } } minStk . add ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] - reduce [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 8 , 4 , 6 , 2 , 3 } ; printFinalPrices ( arr ) ; } }