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: 68
💡 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 Value23154Original Value: |2-3| + |3-1| + |1-5| + |5-4| = 1 + 2 + 4 + 1 = 8Reverse [1,5]23514New Value: |2-3| + |3-5| + |5-1| + |1-4| = 1 + 2 + 4 + 3 = 10Maximum Possible Value: 10
Understanding the Visualization
1
Input
Array with calculated value from adjacent differences
2
Process
Find best subarray to reverse
3
Output
Maximum possible array value
Key Takeaway
🎯 Key Insight: Only boundary connections change when reversing a subarray, enabling O(1) value calculation per attempt
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