Maximum Alternating Subsequence Sum - Problem

The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.

For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4.

Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence).

A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,2,5,3]
Output: 7
💡 Note: Optimal subsequence is [4,2,5] with alternating sum 4-2+5 = 7
Example 2 — Single Element
$ Input: nums = [5,6,7,8]
Output: 8
💡 Note: Take just the largest element [8] with alternating sum 8
Example 3 — Two Elements
$ Input: nums = [6,2,1,2,4,5]
Output: 10
💡 Note: Optimal subsequence is [6,1,5] with alternating sum 6-1+5 = 10

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Maximum Alternating Subsequence Sum INPUT Array: nums 4 i=0 2 i=1 5 i=2 3 i=3 Alternating Sum: a[0] - a[1] + a[2] - a[3]... Goal: Find max alt sum from any subsequence nums = [4, 2, 5, 3] ALGORITHM STEPS 1 Track Two States odd: sum ending at odd pos even: sum ending at even pos 2 Initialize States odd = 0, even = 0 3 Greedy Update new_even = max(even, odd+num) new_odd = max(odd, even-num) 4 Return even Max sum at even position Trace: num | even | odd init: - | 0 | 0 4: 4 | 4 | 0 2: 2 | 4 | 2 5: 5 | 7 | 2 3: 3 | 7 | 4 FINAL RESULT Optimal Subsequence: 4 +ADD 2 skip 5 +ADD 3 skip Calculation: Subsequence: [4, 5] 4 + 5 = 7 (greedy) Output: 7 OK - Maximum Alt Sum Key Insight: The greedy approach tracks two states: best sum ending at even position and odd position. For each element, we decide whether to add it (positive contribution at even) or subtract it (negative at odd). We greedily pick all increases (nums[i] - nums[i-1] when positive). TutorialsPoint - Maximum Alternating Subsequence Sum | Greedy Approach
Asked in
Google 15 Microsoft 12 Amazon 8
52.0K Views
Medium Frequency
~25 min Avg. Time
1.5K 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