Minimum Decrements on Subarrays required to reduce all Array elements to zero | C ++ Program to implement the above approach ; Function to count the minimum number of subarrays that are required to be decremented by 1 ; Base Case ; Initialize ans to first element ; For A [ i ] > A [ i - 1 ] , operation ( A [ i ] - A [ i - 1 ] ) is required ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_operations ( vector < int > & A ) { if ( A . size ( ) == 0 ) return 0 ; int ans = A [ 0 ] ; for ( int i = 1 ; i < A . size ( ) ; i ++ ) { ans += max ( A [ i ] - A [ i - 1 ] , 0 ) ; } return ans ; } int main ( ) { vector < int > A { 1 , 2 , 3 , 2 , 1 } ; cout << min_operations ( A ) << " STRNEWLINE " ; return 0 ; }