Minimum Decrements on Subarrays required to reduce all Array elements to zero

Given an array arr[] consisting of N non-negative integers, the task is to find the minimum number of subarrays that needs to be reduced by 1 such that all the array elements are equal to 0.

Example:

Input: arr[] = {1, 2, 3, 2, 1}
Output: 3
Explanation:
Operation 1: {1, 2, 3, 2, 1} -> {0, 1, 2, 1, 0}
Operation 2: {0, 1, 2, 1, 0} -> {0, 0, 1, 0, 0}
Operation 3: {0, 0, 1, 0, 0} -> {0, 0, 0, 0, 0}

Input: arr[] = {5, 4, 3, 4, 4}
Output: 6
Explanation:
{5, 4, 3, 4, 4} -> {4, 3, 2, 3, 3} -> {3, 2, 1, 2, 2} -> {2, 1, 0, 1, 1} -> {2, 1, 0, 0, 0} -> {1, 0, 0, 0, 0} -> {0, 0, 0, 0, 0}

Approach:
This can be optimally done by traversing the given array from index 0, finding the answer up to index i, where 0 ≤ i < N. If arr[i] ≥ arr[i+1], then (i + 1)th element can eb included in every subarray operation of ith element, thus requiring no extra operations. If arr[i] < arr[i + 1], then (i + 1)th element can be included in every subarray operation of ith element and after all operations, arr[i+1] becomes arr[i+1]-arr[i]. Therefore, we need arr[i+1]-arr[i] extra operations to reduce it zero.



Follow the below steps to solve the problem: