贪心法:
1. 翻转中间,则使用(最小区间最大值-最大区间最小值)*2 + 基准为数组值,这里不一定为正收益
2.翻转头或者尾,则位基准重新计算翻转点
基准=sum(abs(num[i] - num[i - 1]))? (1<=i<nums.size())
class Solution {
public:
int maxValueAfterReverse(vector<int>& nums) {
if (nums.size() <= 1)
return 0;
int sum = 0;
int a = INT_MAX;
int b = INT_MIN;
for (int i = 1; i < nums.size(); ++i) {
sum += abs(nums[i] - nums[i - 1]);
a = min(a, max(nums[i], nums[i - 1]));
b = max(b, min(nums[i], nums[i - 1]));
}
int ans = max(sum, sum + 2 * (b - a));
for (int i = 1; i < nums.size() - 1; i++) {
ans = max(ans, sum - abs(nums[i] - nums[i + 1]) + abs(nums[0] - nums[i + 1]));
ans = max(ans, sum - abs(nums[i - 1] - nums[i]) + abs(nums[i - 1] - nums.back()));
}
return ans;
}
};
|