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 exactlyk, in other words, the subarray nums[i..j] is good if |nums[i] - nums[j]| == k.
Return the maximum sum of a good subarray ofnums. If there are no good subarrays**, return0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: longlongmaximumSubarraySum(vector<int>& nums, int k){ unordered_map<longlong, longlong> freq; longlong 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) return0; return res; } };