Maximum Alternating Subarray Sum Problem
Description
LeetCode Problem 2036.
A subarray of a 0-indexed integer array is a contiguous non-empty sequence of elements within an array.
The alternating subarray sum of a subarray that ranges from index i to j (inclusive, 0 <= i <= j < nums.length) is nums[i] - nums[i+1] + nums[i+2] - ... +/- nums[j].
Given a 0-indexed integer array nums, return the maximum alternating subarray sum of any subarray of nums.
Example 1:
Input: nums = [3,-1,1,2]
Output: 5
Explanation:
The subarray [3,-1,1] has the largest alternating subarray sum.
The alternating subarray sum is 3 - (-1) + 1 = 5.
Example 2:
Input: nums = [2,2,2,2,2]
Output: 2
Explanation:
The subarrays [2], [2,2,2], and [2,2,2,2,2] have the largest alternating subarray sum.
The alternating subarray sum of [2] is 2.
The alternating subarray sum of [2,2,2] is 2 - 2 + 2 = 2.
The alternating subarray sum of [2,2,2,2,2] is 2 - 2 + 2 - 2 + 2 = 2.
Example 3:
Input: nums = [1]
Output: 1
Explanation:
There is only one non-empty subarray, which is [1].
The alternating subarray sum is 1.
Constraints:
1 <= nums.length <= 10^5-10^5 <= nums[i] <= 10^5
Solution
Approach: Dynamic Programming
Let f be the best alternating sum of a subarray ending at nums[i] where nums[i] has a plus sign, and g the best one where nums[i] has a minus sign. Both start at negative infinity.
At each position, a plus sign either starts a new subarray or continues one whose last term had a minus sign: f = max(g, 0) + nums[i]. A minus sign continues a subarray whose last term had a plus sign: g = f - nums[i], where f on the right is the value before the update (see the code). The answer is the maximum of all f and g.
The time complexity is O(n) and the space complexity is O(1), where n is the length of nums.
inf = float("inf")
class Solution:
def maximumAlternatingSubarraySum(self, nums: List[int]) -> int:
ans = f = g = -inf
for x in nums:
f, g = max(g, 0) + x, f - x
ans = max(ans, f, g)
return ans