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 ofnums(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:
1
2
3
Input: nums =[4,2,5,3]Output: 7Explanation: It is optimal to choose the subsequence [4,2,5]with alternating sum(4+5)-2=7.
Example 2:
1
2
3
Input: nums =[5,6,7,8]Output: 8Explanation: It is optimal to choose the subsequence [8]with alternating sum 8.
Example 3:
1
2
3
Input: nums =[6,2,1,2,4,5]Output: 10Explanation: It is optimal to choose the subsequence [6,1,5]with alternating sum(6+5)-1=10.
At each index, we can either choose the current element (and alternate the sign for the next index), or skip it (and keep the sign the same). The goal is to maximize the alternating sum by exploring all possible subsequences recursively.
Define a recursive function that takes the current index and a boolean indicating whether the next element should be added or subtracted. For each call, return the maximum of choosing or skipping the current element. The base case is when the index reaches the end of the array.
Use memoization to avoid redundant calculations in the recursive approach. Store the maximum alternating sum for each subproblem defined by index and sign in a DP table.
Define a recursive function with a DP table indexed by position and sign. For each call, check if the result is already computed. If not, compute the maximum alternating sum by considering both choosing and skipping the current element, and store the result.
Convert the recursive DP with memoization into a bottom-up tabulation. Track two states for each index: the best sum if the current index is even (add) or odd (subtract).
Iterate through the array, maintaining two DP arrays: one for even positions (add) and one for odd positions (subtract). At each step, update both states based on previous values and the current number.
Iterate through the array, updating two variables: even (maximum sum ending with an even index) and odd (maximum sum ending with an odd index). At each step, update both based on the current value and previous states.
publiclongmaxAlternatingSum(int[] nums) {
long even = 0, odd = 0;
for (int a : nums) {
long new_even = Math.max(even, odd + a);
long new_odd = new_even - a;
even = new_even;
odd = new_odd;
}
return even;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funmaxAlternatingSum(nums: IntArray): Long {
var even = 0Lvar odd = 0Lfor (a in nums) {
val new_even = maxOf(even, odd + a)
val new_odd = new_even - a
even = new_even
odd = new_odd
}
return even
}
}
1
2
3
4
5
6
7
8
classSolution:
defmaxAlternatingSum(self, nums: list[int]) -> int:
even, odd =0, 0for a in nums:
new_even = max(even, odd + a)
new_odd = new_even - a
even, odd = new_even, new_odd
return even
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnmax_alternating_sum(nums: Vec<i32>) -> i64 {
let (mut even, mut odd) = (0i64, 0i64);
for&a in&nums {
let new_even = even.max(odd + a asi64);
let new_odd = new_even - a asi64;
even = new_even;
odd = new_odd;
}
even
}
}
This method is inspired by the classic Best Time to Buy and Sell Stock II problem. The idea is to treat each increase in the array as a buy-sell opportunity, accumulating all positive differences between consecutive elements. This approach efficiently computes the maximum alternating sum by summing all upward movements, just like maximizing profit in stock trading.
Iterate through the array, and for each consecutive pair, add the positive difference to the result. This accumulates the maximum possible alternating sum by treating every increase as a buy-sell opportunity.
publiclongmaxAlternatingSum(int[] nums) {
long res = nums[0];
for (int i = 1; i < nums.length; ++i)
res += Math.max(nums[i]- nums[i-1], 0);
return res;
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funmaxAlternatingSum(nums: IntArray): Long {
var res = nums[0].toLong()
for (i in1 until nums.size) {
val diff = nums[i] - nums[i-1]
if (diff > 0) res += diff
}
return res
}
}
1
2
3
4
5
6
7
8
classSolution:
defmaxAlternatingSum(self, nums: list[int]) -> int:
res = nums[0]
for i in range(1, len(nums)):
diff = nums[i] - nums[i-1]
if diff >0:
res += diff
return res
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnmax_alternating_sum(nums: Vec<i32>) -> i64 {
letmut res = nums[0] asi64;
for i in1..nums.len() {
let diff = nums[i] - nums[i-1];
if diff >0 {
res += diff asi64;
}
}
res
}
}
1
2
3
4
5
6
7
8
functionmaxAlternatingSum(nums: number[]):number {
letres=nums[0];
for (leti=1; i<nums.length; i++) {
constdiff=nums[i] -nums[i-1];
if (diff>0) res+=diff;
}
returnres;
}