#1911
Maximum Alternating Subsequence Sum
MediumArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses dynamic programming to keep track of two states: the maximum alternating sum when we include the current number and when we exclude it. This allows us to efficiently compute the maximum sum without exploring all subsequences.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two variables, evenSum and oddSum, to track the maximum sums for even and odd indexed elements respectively.
- 2Step 2: Iterate through each number in the array, updating evenSum and oddSum based on the current number.
- 3Step 3: For each number, calculate the new evenSum as the maximum of the current evenSum and oddSum + current number, and update oddSum as the maximum of the current oddSum and evenSum - current number.
- 4Step 4: Return evenSum as the result since it represents the maximum alternating sum.
solution.py9 lines
1# Full working Python code
2
3def maxAlternatingSum(nums):
4 evenSum = 0
5 oddSum = 0
6 for num in nums:
7 evenSum = max(evenSum, oddSum + num)
8 oddSum = max(oddSum, evenSum - num)
9 return evenSumℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the array, and the space complexity is O(1) since we are using only a constant amount of extra space.
- 1The alternating sum can be maximized by strategically choosing elements based on their indices.
- 2Dynamic programming allows us to efficiently compute the maximum sum without generating all subsequences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.