Reverse Subarray To Maximize Array Value - Problem
You're given an integer array
The value of an array is calculated as the sum of absolute differences between all adjacent elements:
Your task: Select any contiguous subarray and reverse it to achieve the maximum possible array value. You can perform this operation exactly once.
Example: For array
nums and need to maximize its "value" by strategically reversing exactly one subarray.The value of an array is calculated as the sum of absolute differences between all adjacent elements:
|nums[i] - nums[i + 1]| for all valid indices.Your task: Select any contiguous subarray and reverse it to achieve the maximum possible array value. You can perform this operation exactly once.
Example: For array
[2, 3, 1, 5, 4], reversing subarray [3, 1, 5] gives [2, 5, 1, 3, 4] with value |2-5| + |5-1| + |1-3| + |3-4| = 3 + 4 + 2 + 1 = 10 Input & Output
example_1.py — Basic Case
$
Input:
nums = [2,3,1,5,4]
›
Output:
10
💡 Note:
Reverse the subarray [3,1,5] to get [2,5,1,3,4]. The new array value is |2-5| + |5-1| + |1-3| + |3-4| = 3 + 4 + 2 + 1 = 10, which is the maximum possible.
example_2.py — No Improvement Possible
$
Input:
nums = [2,4,9,24,2,1,10]
›
Output:
68
💡 Note:
The original array already has the maximum value. Reversing any subarray would either keep the value the same or decrease it. Original value: |2-4| + |4-9| + |9-24| + |24-2| + |2-1| + |1-10| = 2 + 5 + 15 + 22 + 1 + 9 = 54. After optimal reversal, we can achieve 68.
example_3.py — Two Element Array
$
Input:
nums = [1,2]
›
Output:
1
💡 Note:
With only two elements, the array value is |1-2| = 1. Reversing the entire array gives [2,1] with value |2-1| = 1. No improvement possible.
Constraints
- 1 ≤ nums.length ≤ 3 × 104
- 0 ≤ nums[i] ≤ 105
- You must reverse exactly one subarray (can be single element)
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Baseline
Start with the original array and calculate its total value as the sum of all adjacent differences
2
Analyze Boundaries
For each possible subarray [i,j], determine what connections would change if we reversed it
3
Compute Delta
Calculate the net gain/loss: (new boundary connections) - (old boundary connections)
4
Find Optimum
Choose the reversal that gives the maximum positive change, or keep original if no improvement exists
Key Takeaway
🎯 Key Insight: When reversing a subarray, only the boundary connections change - internal relationships maintain the same absolute differences. This allows us to calculate the impact mathematically without actually performing the reversal, reducing complexity from O(n³) to O(n²).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code