Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
[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.
Example 1:
Input: nums = [4,2,5,3] Output: 7 Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.
Example 2:
Input: nums = [5,6,7,8] Output: 8 Explanation: It is optimal to choose the subsequence [8] with alternating sum 8.
Example 3:
Input: nums = [6,2,1,2,4,5] Output: 10 Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 105Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[4,2,5,3]
[5,6,7,8]
[6,2,1,2,4,5]
maximum-alternating-subarray-sum)maximum-element-sum-of-a-complete-subset-of-indices)maximum-product-of-subsequences-with-an-alternating-sum-equal-to-k)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1911: Maximum Alternating Subsequence Sum
class Solution {
public long maxAlternatingSum(int[] nums) {
int n = nums.length;
long[] f = new long[n + 1];
long[] g = new long[n + 1];
for (int i = 1; i <= n; ++i) {
f[i] = Math.max(g[i - 1] - nums[i - 1], f[i - 1]);
g[i] = Math.max(f[i - 1] + nums[i - 1], g[i - 1]);
}
return Math.max(f[n], g[n]);
}
}
// Accepted solution for LeetCode #1911: Maximum Alternating Subsequence Sum
func maxAlternatingSum(nums []int) int64 {
n := len(nums)
f := make([]int, n+1)
g := make([]int, n+1)
for i, x := range nums {
i++
f[i] = max(g[i-1]-x, f[i-1])
g[i] = max(f[i-1]+x, g[i-1])
}
return int64(max(f[n], g[n]))
}
# Accepted solution for LeetCode #1911: Maximum Alternating Subsequence Sum
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
n = len(nums)
f = [0] * (n + 1)
g = [0] * (n + 1)
for i, x in enumerate(nums, 1):
f[i] = max(g[i - 1] - x, f[i - 1])
g[i] = max(f[i - 1] + x, g[i - 1])
return max(f[n], g[n])
// Accepted solution for LeetCode #1911: Maximum Alternating Subsequence Sum
/**
* [1911] Maximum Alternating Subsequence Sum
*
* 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,<u>2</u>,3,<u>7</u>,2,1,<u>4</u>] (the underlined elements), while [2,4,2] is not.
*
*
* Example 1:
*
*
* Input: nums = [<u>4</u>,<u>2</u>,<u>5</u>,3]
* Output: 7
* Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.
*
*
* Example 2:
*
*
* Input: nums = [5,6,7,<u>8</u>]
* Output: 8
* Explanation: It is optimal to choose the subsequence [8] with alternating sum 8.
*
*
* Example 3:
*
*
* Input: nums = [<u>6</u>,2,<u>1</u>,2,4,<u>5</u>]
* Output: 10
* Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.
*
*
*
* Constraints:
*
*
* 1 <= nums.length <= 10^5
* 1 <= nums[i] <= 10^5
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/maximum-alternating-subsequence-sum/
// discuss: https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/maximum-alternating-subsequence-sum/solutions/3416719/rust-solution/
pub fn max_alternating_sum(nums: Vec<i32>) -> i64 {
let n = nums.len();
let nums = nums.into_iter().map(|v| v as i64).collect::<Vec<i64>>();
let mut a = nums[0];
let mut b = 0;
for i in 1..n {
let v = nums[i];
b = b.max(a - v);
a = a.max(b + v);
}
a.max(b)
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1911_example_1() {
let nums = vec![4, 2, 5, 3];
let result = 7;
assert_eq!(Solution::max_alternating_sum(nums), result);
}
#[test]
fn test_1911_example_2() {
let nums = vec![5, 6, 7, 8];
let result = 8;
assert_eq!(Solution::max_alternating_sum(nums), result);
}
#[test]
fn test_1911_example_3() {
let nums = vec![6, 2, 1, 2, 4, 5];
let result = 10;
assert_eq!(Solution::max_alternating_sum(nums), result);
}
}
// Accepted solution for LeetCode #1911: Maximum Alternating Subsequence Sum
function maxAlternatingSum(nums: number[]): number {
const n = nums.length;
const f: number[] = new Array(n + 1).fill(0);
const g = f.slice();
for (let i = 1; i <= n; ++i) {
f[i] = Math.max(g[i - 1] + nums[i - 1], f[i - 1]);
g[i] = Math.max(f[i - 1] - nums[i - 1], g[i - 1]);
}
return Math.max(f[n], g[n]);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.