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.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: target = [1,2,3,2,1]
Output: 3
Explanation: We need at least 3 operations to form the target array from the initial array.
[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).
[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).
[1,2,2,2,1] increment 1 at index 2.
[1,2,3,2,1] target array is formed.
Example 2:
Input: target = [3,1,1,2]
Output: 4
Explanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]
Example 3:
Input: target = [3,1,5,4,2]
Output: 7
Explanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].
Constraints:
- 1 <= target.length <= 105
- 1 <= target[i] <= 105
在上升沿开始的时候设置一个基准值, 上升时我们将每个当前值与上一个值的差值纳入到答案中。下降时如果当前值在基准值之上, 我们不做任何处理, 因为当前的高度值已经在上升沿的时候计过一次了。只有当前值低于基准值的时候, 我们才会把基准值与当前值的差值计入答案, 同时我们把基准值调整到与当前值相同。最后答案还需要加上结束时的基准值, 这实际就是把基准值以下的值都作为一个 subarray 来进行处理。
impl Solution {
pub fn min_number_operations(target: Vec<i32>) -> i32 {
let mut base = target[0];
let mut prev = target[0];
let mut ans = 0;
for &n in target[1..].into_iter() {
if n >= prev {
ans += n - prev;
prev = n;
continue;
}
if n < base {
ans += base - n;
base = n;
}
prev = n;
}
ans += base;
ans
}
}