Skip to content

1526. Minimum Number of Increments on Subarrays to Form a Target Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  int minNumberOperations(vector<int>& target) {
    int ans = target.front();

    for (int i = 1; i < target.size(); ++i)
      if (target[i] > target[i - 1])
        ans += target[i] - target[i - 1];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public int minNumberOperations(int[] target) {
    int ans = target[0];

    for (int i = 1; i < target.length; ++i)
      if (target[i] > target[i - 1])
        ans += target[i] - target[i - 1];

    return ans;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def minNumberOperations(self, target: list[int]) -> int:
    ans = target[0]

    for a, b in zip(target, target[1:]):
      if a < b:
        ans += b - a

    return ans