[LeetCode] Maximum Sum of Distinct Subarrays With Length K

2461. Maximum Sum of Distinct Subarrays With Length K

You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:

  • The length of the subarray is k, and
  • All the elements of the subarray are distinct.

Return the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return 0.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
long long maximumSubarraySum(vector<int>& A, int k) {
long long res = 0, now = 0;
unordered_map<int, int> freq;
for(int i = 0; i < A.size(); i++) {
freq[A[i]] += 1;
now += A[i];
if(i >= k) {
if(--freq[A[i-k]] == 0) freq.erase(A[i-k]);
now -= A[i-k];
}
if(freq.size() == k) res = max(res, now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/06/PS/LeetCode/maximum-sum-of-distinct-subarrays-with-length-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.