Problem Description
Given a 0-indexed integer array, an alternating subarray is defined as a contiguous non-empty sequence where the elements are added and subtracted in an alternating pattern, starting with addition. For any subarray from index i to j, its alternating sum is computed as nums[i] - nums[i+1] + nums[i+2] - ... (with the appropriate sign for the last element). The task is to find the maximum alternating subarray sum among all possible subarrays.
Key Insights
- The alternating sum can be computed with a dynamic programming approach where at each index we track the maximum sum ending at that index when the index contributes positively (even position in the alternating pattern) and when it contributes negatively (odd position).
- We can restart a subarray at any index, treating that element as the start (with a positive sign).
- By maintaining only the previous state (even and odd sums), the solution can be computed in O(n) time and O(1) space.
- A careful initialization is required since the first element always starts as a positive contribution.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
We maintain two variables:
- dp_even – the maximum alternating subarray sum ending at the current index where the current element is added.
- dp_odd – the maximum alternating subarray sum ending at the current index where the current element is subtracted.
For the first element: • dp_even = nums[0] (since the subarray containing only nums[0] contributes nums[0]) • dp_odd is initialized to negative infinity because we haven't performed a subtraction yet.
For each subsequent index i: • To update dp_even (the sum if nums[i] is added), we can either start a new subarray at position i (which gives a sum of nums[i]) or extend a previous subarray that ended with a subtraction by adding the current element (dp_odd + nums[i]). • To update dp_odd (the sum if nums[i] is subtracted), we can only extend a subarray which previously ended with an addition (dp_even - nums[i]).
The overall answer is the maximum dp_even over all indices since valid subarrays must start with a positive sign.