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.

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.

Example 1
Inputnums = [4,2,5,3]
Output7
It is optimal to choose the subsequence [4, 2, 5] with alternating sum (4 + 5) - 2 = 7.
Example 2
Inputnums = [5,6,7,8]
Output8
It is optimal to choose the subsequence [8] with alternating sum 8.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate