DDSA Solutions

1911. Maximum Alternating Subsequence Sum

Time: O(n)
Space: O(1)

Problem Overview

Maximum Alternating Subsequence Sum (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Dynamic Programming pattern in coding interviews. DP with two states (even/odd position sums); greedily add or skip each element.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

DP with two states (even/odd position sums); greedily add or skip each element.

Related patterns: Array, Dynamic Programming, Greedy

1911.cs
C#
// Approach: DP with two states (even/odd position sums); greedily add or skip each element.
// Time: O(n) Space: O(1)

public class Solution
{
    public long MaxAlternatingSum(int[] nums)
    {
        long even = 0; // the maximum alternating sum ending in an even index
        long odd = 0;  // the maximum alternating sum ending in an odd index

        foreach (var num in nums)
        {
            even = Math.Max(even, odd + num);
            odd = even - num;
        }

        return even;
    }
}
Was this solution helpful?

Related Problems