Maximum Alternating Subarray Sum - Problem
Maximum Alternating Subarray Sum

You're given an array of integers and need to find the maximum alternating sum of any contiguous subarray. An alternating sum starts with a positive sign and alternates between positive and negative: nums[i] - nums[i+1] + nums[i+2] - nums[i+3] + ...

For example, given array [4,2,5,3]:
• Subarray [4,2,5] has alternating sum: 4 - 2 + 5 = 7
• Subarray [2,5,3] has alternating sum: 2 - 5 + 3 = 0
• Single element [5] has alternating sum: 5

Your goal: Return the maximum possible alternating sum from any subarray.

Input & Output

example_1.py — Basic Case
$ Input: nums = [4,2,5,3]
Output: 7
💡 Note: The optimal subarray is [4,2,5] with alternating sum 4 - 2 + 5 = 7. This gives the maximum possible alternating sum.
example_2.py — All Negative
$ Input: nums = [5,6,7,8]
Output: 8
💡 Note: When all elements form a non-decreasing sequence, the best strategy is to take just the largest single element. Subarray [8] gives sum = 8.
example_3.py — Single Element
$ Input: nums = [6]
Output: 6
💡 Note: With only one element, the alternating sum is just that element itself. The subarray [6] gives sum = 6.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • All array elements are positive integers

Visualization

Tap to expand
Stock Trading Visualization$4BUY$2SELL?$5BUY$3SELL?Skip: -$2 loss+$5 profit!Skip: -$3 lossTrading DecisionsPosition 0 (Price $4):• Buy state: max(0, 0+4) = 4 ← Choose to buy• Sell state: max(0, 0-4) = 0Position 1 (Price $2):• Buy state: max(4, 0+2) = 4 ← Keep previous buy• Sell state: max(0, 4-2) = 2Position 2 (Price $5):• Buy state: max(4, 2+5) = 7 ← New maximum!Sequence: BUY($4) → SKIP($2) → BUY($5)Alternating sum: +4 - 2 + 5 = 7Optimal Strategy Found!The DP approach finds this automaticallywithout trying all combinations.🎯 Key Insight:Track the best profit in each state (buying vs selling) - optimal substructure!
Understanding the Visualization
1
Start with no position
buy=0, sell=0 - we haven't made any trades yet
2
See stock price 4
We can buy it (buy=4) or stay neutral. Selling would lose money.
3
See stock price 2
If we bought at 4, selling at 2 loses money. Better to stay at buy=4.
4
See stock price 5
Now we can sell at 5 after buying sequence, giving us profit of 7!
Key Takeaway
🎯 Key Insight: By maintaining two states (buy/sell), we can make optimal local decisions that lead to the global maximum without exploring all possible subarrays.
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 23
42.3K Views
Medium-High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen