Reverse Subarray To Maximize Array Value - Problem

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 the maximum possible value of the final array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,1,5,4]
Output: 10
💡 Note: Reverse subarray [1,5] to get [2,3,5,1,4]. Value = |2-3| + |3-5| + |5-1| + |1-4| = 1 + 2 + 4 + 3 = 10
Example 2 — No Improvement
$ Input: nums = [2,4,9,24,2,1,10]
Output: 54
💡 Note: The original array already gives maximum value. No reversal improves it.
Example 3 — Single Element
$ Input: nums = [5]
Output: 0
💡 Note: Only one element, so no adjacent pairs exist. Value is 0.

Constraints

  • 1 ≤ nums.length ≤ 3 × 104
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Reverse Subarray To Maximize Array Value INPUT nums array: 2 i=0 3 i=1 1 i=2 5 i=3 4 i=4 Original Value: |2-3| + |3-1| + |1-5| + |5-4| = 1 + 2 + 4 + 1 = 8 Array Value Definition: sum of |nums[i] - nums[i+1]| for all adjacent pairs Goal: Reverse one subarray to maximize this value ALGORITHM STEPS 1 Calculate base value Sum all |nums[i]-nums[i+1]| 2 Check boundary cases Reverse from start or to end 3 Find max/min pairs Track min(max) and max(min) 4 Compute max gain Gain = 2*(maxMin - minMax) Best Reversal: [3,1,5] Before: [2,3,1,5,4] After: [2,5,1,3,4] New value: 10 (gain of 2) FINAL RESULT Optimal reversed array: 2 5 1 3 4 Green = reversed subarray New Value Calculation: |2-5| + |5-1| + |1-3| + |3-4| = 3 + 4 + 2 + 1 = 10 Output 10 Maximum array value = 10 Improvement: 8 --> 10 OK - Optimal! Key Insight: When reversing subarray [i..j], only boundaries change: (nums[i-1],nums[i]) and (nums[j],nums[j+1]). The optimal gain comes from maximizing: 2 * (maxOfMins - minOfMaxs) for all adjacent pairs. This allows O(n) solution by tracking min(max(a,b)) and max(min(a,b)) across all pairs. TutorialsPoint - Reverse Subarray To Maximize Array Value | Mathematical Optimization Approach
Asked in
Google 15 Facebook 12 Microsoft 8
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen