Maximum Alternating Subsequence Sum

Aug 9, 2021


When I was doing leetcode problems, I saw a very interesting problem - 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,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.

The basic idea I have here is to keep a mono-decreasing queue, while each time we see an increasing sequence, we add the front minus back into the total sum greedily. Both time and space will be O(n).

Some may argue that the above approach is O(n) space, which does not look too good. By looking at the algorithm carefully, we notice that all that matters is the front and the back of the mono-queue. So we only have to keep the front and the back values. See below for an O(1) space solution. Time is still O(n).

Runtime: 156 ms, faster than 84.48% of C++ online submissions for Maximum Alternating Subsequence Sum.

Memory Usage: 91.1 MB, less than 60.15% of C++ online submissions for Maximum Alternating Subsequence Sum.