Modify given array by reducing each element by its next smaller element | C # program for the above approach ; Function to print the readonly 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 readonly array ; Driver Code ; Given array ; Function call
using System ; using System . Collections . Generic ; class GFG { static void printFinalPrices ( int [ ] arr ) { Stack < int > minStk = new Stack < int > ( ) ; int n = arr . Length ; int [ ] reduce = new int [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( minStk . Count != 0 ) { if ( minStk . Peek ( ) <= arr [ i ] ) { reduce [ i ] = minStk . Peek ( ) ; } else { while ( minStk . Count != 0 && ( minStk . Peek ( ) > arr [ i ] ) ) { minStk . Pop ( ) ; } if ( minStk . Count != 0 ) { reduce [ i ] = minStk . Peek ( ) ; } } } minStk . Push ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] - reduce [ i ] + " ▁ " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 8 , 4 , 6 , 2 , 3 } ; printFinalPrices ( arr ) ; } }