Minimum Number of Increments on Subarrays to Form a Target Array

hard monotonic stack array greedy

Problem

You start with an array initial of the same length as target, filled entirely with zeros. In one operation you pick any contiguous subarray of initial and add 1 to every element of it. Return the minimum number of such operations needed to turn initial into target.

Inputtarget = [1,2,3,2,1]
Output3
Add 1 over [0..4], then 1 over [1..3], then 1 at index 2.
Inputtarget = [3,1,1,2]
Output4
3 + max(0,1−3) + max(0,1−1) + max(0,2−1) = 3 + 0 + 0 + 1 = 4.

def min_number_operations(target):
    ops = target[0]
    for i in range(1, len(target)):
        if target[i] > target[i - 1]:
            ops += target[i] - target[i - 1]
    return ops
function minNumberOperations(target) {
  let ops = target[0];
  for (let i = 1; i < target.length; i++) {
    if (target[i] > target[i - 1]) {
      ops += target[i] - target[i - 1];
    }
  }
  return ops;
}
int minNumberOperations(int[] target) {
    int ops = target[0];
    for (int i = 1; i < target.length; i++) {
        if (target[i] > target[i - 1]) {
            ops += target[i] - target[i - 1];
        }
    }
    return ops;
}
int minNumberOperations(vector<int>& target) {
    int ops = target[0];
    for (int i = 1; i < (int)target.size(); i++) {
        if (target[i] > target[i - 1]) {
            ops += target[i] - target[i - 1];
        }
    }
    return ops;
}
Time: O(n) Space: O(1)