Skip to main content
Back to problems
#1526
Hard Algorithms

Minimum number of increments on subarrays to form a target array

Array Dynamic Programming Stack Greedy Monotonic Stack
78.1% acceptance
Feb 25, 2026
2132
108
You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_number_operations(target: Vec<i32>) -> i32 {
    // Answer = sum of max(0, target[i] - target[i-1]) where target[-1] = 0
    target[0] + target.windows(2)
      .map(|w| (w[1] - w[0]).max(0))
      .sum::<i32>()
  }
}