#1911

Maximum Alternating Subsequence Sum

specialist · 725 · lc medium +31 · verified · 59.1% accepted · 1,430 likes · top 56%

Description

The alternating sum of a 0-indexed array is the sum of even-indexed elements minus the sum of odd-indexed elements.

Given an array nums, choose a subsequence of nums (preserving relative order, possibly empty) that maximizes the alternating sum, and return that maximum value.

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.

Code

1
2