[LeetCode] Maximum Good Subarray Sum

3026. Maximum Good Subarray Sum

You are given an array nums of length n and a positive integer k.

A subarray of nums is called good if the absolute difference between its first and last element is exactly k, in other words, the subarray nums[i..j] is good if |nums[i] - nums[j]| == k.

Return the maximum sum of a good subarray of nums. If there are no good subarrays**, return 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
unordered_map<long long, long long> freq;
long long sum = 0, res = LLONG_MIN;
for(auto& x : nums) {
sum += x;
if(freq.count(x + k)) res = max(res, sum - freq[x+k] + (x + k));
if(freq.count(x - k)) res = max(res, sum - freq[x-k] + (x - k));
if(!freq.count(x)) freq[x] = sum;
freq[x] = min(freq[x], sum);
}
if(res == LLONG_MIN) return 0;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/02/04/PS/LeetCode/maximum-good-subarray-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.