-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumAlternatingSubsquenceSum.java
More file actions
41 lines (41 loc) · 1.6 KB
/
MaximumAlternatingSubsquenceSum.java
File metadata and controls
41 lines (41 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*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*/
import java.util.*;
class MaximumAlternatingSubsquenceSum{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int nums[]=new int[n];
for(int i=0;i<n;i++){
nums[i]=sc.nextInt();
}
System.out.print(maxAlternatingSum(nums));
}
public static long maxAlternatingSum(int[] nums){
long add=0,sub=0;
for(int i=nums.length-1;i>=0;i--){
long newAdd=Math.max(add,nums[i]+sub);
long newSub=Math.max(sub,add-nums[i]);
add=newAdd;
sub=newSub;
}
return add;
}
}