LeetCode每日一题(1526. Minimum Number of Increments on Subarrays to Form a Target Array)

给定目标数组target,从初始全为0的相同大小的数组开始,每次可以选择任意子数组并将其所有元素加1。返回形成目标数组所需的最小操作数。示例表明,解答将适合32位整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值