Minimum Decrements on Subarrays required to reduce all Array elements to zero | 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
function min_operations ( A ) { if ( A . length == 0 ) return 0 ; let ans = A [ 0 ] ; for ( let i = 1 ; i < A . length ; i ++ ) { ans += Math . max ( A [ i ] - A [ i - 1 ] , 0 ) ; } return ans ; } let A = [ 1 , 2 , 3 , 2 , 1 ] ; document . write ( min_operations ( A ) ) ;