Maximum Alternating Subarray Sum With One Deletion Problem
Description
LeetCode Problem 4072.
You are given an integer array nums.
You may delete at most one element from nums, then choose a subarray of the resulting array.
Return the maximum possible alternating sum of the chosen subarray.
The alternating sum of an array is the sum of its elements at even indices minus the sum of its elements at odd indices. The chosen subarray is reindexed starting from 0 before calculating its alternating sum.
Example 1:
Input: nums = [5,-5,1]
Output: 11
Explanation:
Choose not to delete an element and select the entire array. Its alternating sum is 5 - (-5) + 1 = 11, which is the maximum possible.
Example 2:
Input: nums = [10,-5,-100]
Output: 110
Explanation:
Delete nums[1] = -5 to obtain [10,-100], then select the entire resulting array. Its alternating sum is 10 - (-100) = 110, which is the maximum possible.
Example 3:
Input: nums = [4,7]
Output: 7
Explanation:
Choose not to delete an element and select the subarray [7]. Its alternating sum is 7, which is the maximum possible.
Constraints:
1 <= nums.length <= 10^5-10^5 <= nums[i] <= 10^5
Solution
Approach: Dynamic programming with four states
Scan the array and keep, for the subarray that ends at the current element, the best alternating sum in four situations:
f0/f1: nothing deleted so far, and the last element of the subarray is added (+) / subtracted (-).g0/g1: one element was already deleted, with the same meaning for the sign of the last kept element.
For the next element x:
f0 = max(x, f1 + x)(start a new subarray atx, or addxafter a subtracted element) andf1 = f0_old - x.g0 = max(g1 + x, f0_old)andg1 = max(g0_old - x, f1_old). The first term keepsx; the second deletesx, so the last kept element and its sign stay as they were.
The answer is the largest value seen in any of the four states. Sums reach about 10^10, so use 64-bit integers.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
NEG = -10**18
# f0 / f1: best sum of a subarray ending at the current element, no deletion yet,
# whose last element has sign + / -. g0 / g1: the same, after one deletion.
f0 = f1 = g0 = g1 = NEG
ans = NEG
for x in nums:
n0 = max(x, f1 + x)
n1 = f0 - x
m0 = max(g1 + x, f0) # keep x, or delete x
m1 = max(g0 - x, f1)
f0, f1, g0, g1 = n0, n1, m0, m1
ans = max(ans, f0, f1, g0, g1)
return ans