[LeetCode] Maximum Alternating Subarray Sum

2036. Maximum Alternating Subarray Sum

A subarray of a 0-indexed integer array is a contiguous non-empty sequence of elements within an array.

The alternating subarray sum of a subarray that ranges from index i to j (inclusive, 0 <= i <= j < nums.length) is nums[i] - nums[i+1] + nums[i+2] - … +/- nums[j].

Given a 0-indexed integer array nums, return the maximum alternating subarray sum of any subarray of nums.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
long long helper(vector<int>& A, int p) {
long long psum = 0, mi = 0, ma = 0, res = LLONG_MIN, n = A.size();
for(int i = p; i < n; i++) {
if((i - p) & 1) psum -= A[i];
else psum += A[i];
res = max({res, psum, psum - mi, psum - ma});

if((i - p) & 1) {
mi = min(mi, psum);
ma = max(ma, psum);
}
}
return res;
}
public:
long long maximumAlternatingSubarraySum(vector<int>& A) {
return max(helper(A, 0), helper(A, 1));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/22/PS/LeetCode/maximum-alternating-subarray-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.