Maximum Pulse Value After One Subarray Rotation Problem
Description
LeetCode Problem 4058.
You are given an integer array nums of length n.
Define the pulse value of an integer array arr as the alternating sum starting at index 0: pulse(arr) = arr[0] - arr[1] + arr[2] - arr[3] + ....
You may perform at most one operation on nums:
- Choose two indices
landrsuch that0 <= l < r < n. - Left-rotate the subarray
nums[l..r]by exactly one position. For example,[a, b, c, d]becomes[b, c, d, a].
Return the maximum pulse value that can be obtained after performing at most one such operation.
Example 1:
Input: nums = [1,5,2]
Output: 6
Explanation:
- The original pulse value is 1 - 5 + 2 = -2.
- Rotate the subarray nums[0..1] from [1, 5] to [5, 1].
- The resulting array is [5, 1, 2] and its pulse value is 5 - 1 + 2 = 6, which is the maximum possible.
Example 2:
Input: nums = [6,4,3]
Output: 7
Explanation:
- The original pulse value is 6 - 4 + 3 = 5.
- Rotate the subarray nums[1..2] from [4, 3] to [3, 4].
- The resulting array is [6, 3, 4] and its pulse value is 6 - 3 + 4 = 7, which is the maximum possible.
Example 3:
Input: nums = [9,7]
Output: 2
Explanation:
The original pulse value is 9 - 7 = 2, which is already maximum. Thus, no rotation is required.
Constraints:
1 <= n == nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Prefix Sums by Parity
Let b[k] = nums[k] for even k and -nums[k] for odd k, and let P[k] be the prefix sums of b. The pulse value of the original array is P[n-1].
Rotating nums[l..r] to the left moves nums[l] to position r and shifts the elements l+1..r one place left. Every shifted element changes sign. Working out the change in the pulse value gives:
- if
r - lis even, the gain is2 * (P[l] - P[r]); - if
r - lis odd, the gain is2 * (P[l-1] - P[r]), withP[-1] = 0.
So for each r we want the largest P[l] over earlier l with the same parity as r, and the largest P[l-1] over earlier l with the opposite parity. Keep these four running maxima while scanning left to right. The answer is P[n-1] plus the best gain, where doing nothing counts as a gain of 0.
Sums reach about 10^14, so use 64-bit integers.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxValue(self, nums: List[int]) -> int:
n = len(nums)
inf = float("inf")
# p[k] = alternating sum of nums[0..k]; before[k] = p[k-1]
p = 0
# best[d][parity]: best value of P_l (d=0) or P_{l-1} (d=1) over l with that parity
same = [-inf, -inf]
diff = [-inf, -inf]
gain = 0
for r in range(n):
prev = p
p += nums[r] if r % 2 == 0 else -nums[r]
# rotating [l..r]: same parity -> 2*(P_l - P_r), different parity -> 2*(P_{l-1} - P_r)
gain = max(gain, 2 * (same[r % 2] - p), 2 * (diff[1 - r % 2] - p))
same[r % 2] = max(same[r % 2], p)
diff[r % 2] = max(diff[r % 2], prev)
return p + gain