Reverse Subarray To Maximize Array Value — LeetCode 1330 Python Solution
HardGreedyArrayMath
- Problem
- #1330
- Pattern
- Greedy
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- 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.
Python solution
Python
class Solution:
def maxValueAfterReverse(self, nums: List[int]) -> int:
ans = s = sum(abs(x - y) for x, y in pairwise(nums))
for x, y in pairwise(nums):
ans = max(ans, s + abs(nums[0] - y) - abs(x - y))
ans = max(ans, s + abs(nums[-1] - x) - abs(x - y))
for k1, k2 in pairwise((1, -1, -1, 1, 1)):
mx, mi = -inf, inf
for x, y in pairwise(nums):
a = k1 * x + k2 * y
b = abs(x - y)
mx = max(mx, a - b)
mi = min(mi, a + b)
ans = max(ans, s + max(mx - mi, 0))
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array nums |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1330. Reverse Subarray To Maximize Array Value is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1330. Reverse Subarray To Maximize Array Value?
- LeetCode 1330. Reverse Subarray To Maximize Array Value is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1330. Reverse Subarray To Maximize Array Value?
- The Python solution on this page runs in O(n), where n is the length of the array nums.
- What is the space complexity of LeetCode 1330. Reverse Subarray To Maximize Array Value?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1330. Reverse Subarray To Maximize Array Value cover?
- LeetCode 1330. Reverse Subarray To Maximize Array Value is tagged Greedy, Array and Math on LeetCode.