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 * 10^4`
• `-10^5 <= nums[i] <= 10^5`

``````2 | 3 1 5 | 4
a   b   c   d
``````

``````2 | 3 1 5 | 3
a   b   c   d
``````

``````4 | 3 1 5 | 3
a   b   c   d
``````

``````class Solution {
public:
int maxValueAfterReverse(vector<int>& nums) {
int total = 0, res = 0, minMax = INT_MAX, maxMin = INT_MIN, n = nums.size();
for (int i = 0; i < n - 1; ++i) {
int diff = abs(nums[i] - nums[i + 1]);
total += diff;
res = max(res, abs(nums[0] - nums[i + 1]) - diff);
res = max(res, abs(nums[n - 1] - nums[i]) - diff);
minMax = min(minMax, max(nums[i], nums[i + 1]));
maxMin = max(maxMin, min(nums[i], nums[i + 1]));
}
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1330

https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/

https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/solutions/489882/o-n-solution-with-explanation/

https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/solutions/489743/java-c-python-one-pass-o-1-space/

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation