g1901_2000.s1911_maximum_alternating_subsequence_sum.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g1901_2000.s1911_maximum_alternating_subsequence_sum;
// #Medium #Array #Dynamic_Programming #2022_05_14_Time_12_ms_(51.75%)_Space_97.4_MB_(59.03%)
/**
* 1911 - Maximum Alternating Subsequence Sum\.
*
* Medium
*
* 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.
*
* **Constraints:**
*
* * 1 <= nums.length <= 105
* * 1 <= nums[i] <= 105
**/
public class Solution {
public long maxAlternatingSum(int[] nums) {
int n = nums.length;
long even = nums[0];
long odd = 0;
for (int i = 1; i < n; i++) {
even = Math.max(even, Math.max(odd + nums[i], nums[i]));
odd = Math.max(odd, Math.max(even - nums[i], 0));
}
return Math.max(even, odd);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy