给你一个整数数组 nums 。「 数组值」定义为所有满足 0 <= i < nums.length-1 的 |nums[i]-nums[i+1]| 的和。
你可以选择给定数组的任意子数组,并将该子数组翻转。但你只能执行这个操作 一次 。
请你找到可行的最大 数组值 。
示例 1:
输入:nums = [2,3,1,5,4]
输出:10
解释:通过翻转子数组 [3,1,5] ,数组变成 [2,5,1,3,4] ,数组值为 10 。
示例 2:
输入:nums = [2,4,9,24,2,1,10]
输出:68
提示:
1 <= nums.length <= 3*10^4
-10^5 <= nums[i] <= 10^5
思路:题解中看了两种不错的解法,都是对公式的进一步剖析,这里我不再废话,贴出两个讲解,我用的第二种方法。
class Solution {
public int maxValueAfterReverse(int[] nums) {
int ans=0,all=0;
int n=nums.length;
for(int i=0;i<n-1;i++)
all+=Math.abs(nums[i]-nums[i+1]);
int mn=Math.max(nums[0], nums[1]);
int mx=Math.min(nums[0], nums[1]);
for(int i=1;i<n;i++) {
int t1=Math.min(nums[i], nums[i-1]);
int t2=Math.max(nums[i], nums[i-1]);
if(mn<t1) ans=Math.max(ans, t1-mn);
if(mx>t2) ans=Math.max(ans, mx-t2);
mn=Math.min(mn, t2);
mx=Math.max(mx, t1);
}
ans*=2;
for(int i=1;i<n;i++) {
ans=Math.max(ans, Math.abs(nums[i]-nums[0])-Math.abs(nums[i]-nums[i-1]));
ans=Math.max(ans, Math.abs(nums[n-i-1]-nums[n-1])-Math.abs(nums[n-i]-nums[n-i-1]));
}
return all+ans;
}
}