Modify given array by reducing each element by its next smaller element | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printFinalPrices ( vector < int > & arr ) { stack < int > minStk ; int n = arr . size ( ) ; vector < int > reduce ( n , 0 ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( ! minStk . empty ( ) ) { if ( minStk . top ( ) <= arr [ i ] ) { reduce [ i ] = minStk . top ( ) ; } else { while ( ! minStk . empty ( ) && ( minStk . top ( ) > arr [ i ] ) ) { minStk . pop ( ) ; } if ( ! minStk . empty ( ) ) { reduce [ i ] = minStk . top ( ) ; } } } minStk . push ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] - reduce [ i ] << " ▁ " ; } int main ( ) { vector < int > arr = { 8 , 4 , 6 , 2 , 3 } ; printFinalPrices ( arr ) ; return 0 ; }