LeetCode每日一题(1330. Reverse Subarray To Maximize Array Value)

You are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1.

You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.

Find maximum possible value of the final array.

Example 1:

Input: nums = [2,3,1,5,4]
Output: 10

Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.

Example 2:

Input: nums = [2,4,9,24,2,1,10]
Output: 68

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -105 <= nums[i] <= 105

答案看懂了, 但是最终推出的方法, 表现在数组上的意义是什么, 真想不出来, 可能这就是数学吧。大家自己看答案吧, 里面讲的很清楚, 我就不在这赘述了



impl Solution {
    pub fn max_value_after_reverse(nums: Vec<i32>) -> i32 {
        let val: i32 = nums.windows(2).map(|w| (w[0] - w[1]).abs()).sum();
        let mut min = i32::MAX;
        let mut max = i32::MIN;
        for w in nums.windows(2) {
            min = min.min(w[0].max(w[1]));
            max = max.max(w[0].min(w[1]));
        }
        let mut ans = val + 0.max((max - min) * 2);
        for w in nums.windows(2) {
            ans = ans.max(val - (w[0] - w[1]).abs() + (w[1] - nums[0]).abs());
            ans = ans.max(val - (w[0] - w[1]).abs() + (w[0] - nums[nums.len() - 1]).abs());
        }
        ans
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值