#3229
Hard Algorithms Minimum operations to make array equal to target
Array Dynamic Programming Stack Greedy Monotonic Stack
41.3% acceptance
Feb 25, 2026
293
12
You are given two positive integer arrays nums and target, of the same length.
In a single operation, you can select any subarray of nums and increment each element within
that subarray by 1 or decrement each element within that subarray by 1.
Return the minimum number of operations required to make nums equal to the array target.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_operations(nums: Vec<i32>, target: Vec<i32>) -> i64 {
let n = nums.len();
let mut ans = 0i64;
let mut prev_pos = 0i64; // previous positive diff
let mut prev_neg = 0i64; // previous negative diff (stored as positive)
for i in 0..n {
let d = target[i] as i64 - nums[i] as i64;
let pos = d.max(0);
let neg = (-d).max(0);
// Rising slope of positive part
ans += (pos - prev_pos).max(0);
// Rising slope of negative part
ans += (neg - prev_neg).max(0);
prev_pos = pos;
prev_neg = neg;
}
ans
}
}