Skip to content

1911. Maximum Alternating Subsequence Sum 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  long long maxAlternatingSum(vector<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

    for (const int num : nums) {
      even = max(even, odd + num);
      odd = even - num;
    }

    return even;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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

    for (final int num : nums) {
      even = Math.max(even, odd + num);
      odd = even - num;
    }

    return even;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def maxAlternatingSum(self, nums: list[int]) -> int:
    even = 0  # the maximum alternating sum ending in an even index
    odd = 0  # the maximum alternating sum ending in an odd index

    for num in nums:
      even = max(even, odd + num)
      odd = even - num

    return even