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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public: int maxValueAfterReverse(vector<int>& A) { int sum = 0, rev = 0, ma = -1e5, mi = 1e5, n = A.size(); for(int i = 0; i < n - 1; i++) { sum += abs(A[i] - A[i + 1]); rev = max(rev, abs(A[0] - A[i + 1]) - abs(A[i] - A[i + 1])); rev = max(rev, abs(A[n - 1] - A[i]) - abs(A[i] - A[i + 1])); mi = min(mi, max(A[i], A[i + 1])); ma = max(ma, min(A[i], A[i + 1])); } return sum + max(rev, (ma - mi) * 2); } };
|