The Maximum Alternating Subsequence Sum problem gives you an array of positive integers. You need to select a subsequence (not necessarily contiguous) and apply alternating signs to its elements: the first element is added, the second is subtracted, the third is added, and so on. Your goal is to maximize this alternating sum.
This is a classic Dynamic Programming problem that heavily resembles the famous "Best Time to Buy and Sell Stock" series. Interviewers ask it because the math is virtually identical to buying (subtracting) and selling (adding) a stock. It tests if a candidate can optimize a 2D DP array down to space using just two tracking variables.
The problem relies on Dynamic Programming with state transition. At any given step, your subsequence can end on an "even" index (meaning the last element was added) or an "odd" index (meaning the last element was subtracted). We maintain two variables:
even_sum: Max sum ending with an addition.odd_sum: Max sum ending with a subtraction.
For every element in the array, we update the states simultaneously:new_even_sum = max(even_sum, odd_sum + element)new_odd_sum = max(odd_sum, even_sum - element)Array: [4, 2, 5, 3]
Initialize even_sum = 0, odd_sum = 0.
4:
new_even = max(0, 0 + 4) = 4.new_odd = max(0, 0 - 4) = 0. (We don't go negative because we could just pick an empty subsequence).even = 4, odd = 0.2:
new_even = max(4, 0 + 2) = 4.new_odd = max(0, 4 - 2) = 2.even = 4, odd = 2.5:
new_even = max(4, 2 + 5) = 7.new_odd = max(2, 4 - 5) = 2.even = 7, odd = 2.3:
new_even = max(7, 2 + 3) = 7.new_odd = max(2, 7 - 3) = 4.even = 7, odd = 4.
The maximum alternating subsequence sum is even_sum (7). (Subsequence [4, 2, 5]: ).A major pitfall is updating even_sum and then immediately using the new even_sum to calculate the odd_sum in the same loop iteration. This causes you to essentially add and subtract the exact same element simultaneously. You must use temporary variables to store the new calculations and update both even_sum and odd_sum at the very end of the loop iteration.
To easily understand the Maximum Alternating Subsequence Sum coding problem, treat it like stock trading. Adding a number is "selling a stock", and subtracting a number is "buying a stock". You start with 0 money. If you buy at 2 and sell at 5, your profit is . The logic is a perfect 1:1 mapping, making the DP transitions much more intuitive to reason about.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find the Maximum Length of Valid Subsequence I | Medium | Solve | |
| Maximum Absolute Sum of Any Subarray | Medium | Solve | |
| Solving Questions With Brainpower | Medium | Solve | |
| Best Sightseeing Pair | Medium | Solve | |
| Find the Maximum Length of Valid Subsequence II | Medium | Solve |