---
# System prepended metadata

title: 2461. Maximum Sum of Distinct Subarrays With Length K
tags: [Leetcode, Sliding Window, Medium]

---

# 2461. Maximum Sum of Distinct Subarrays With Length K
###### tags: `Leetcode` `Medium` `Sliding Window`
Link: https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/description/
## 思路
map记录每个元素出现的次数
用map的size来判断unique元素的个数
## Code
```java=
class Solution {
    public long maximumSubarraySum(int[] nums, int k) {
        long max = 0, curr = 0;
        Map<Integer, Integer> cnt = new HashMap<>();
        for(int i=0; i<nums.length; i++){
            curr += nums[i];
            cnt.put(nums[i], cnt.getOrDefault(nums[i], 0)+1);
            if(i>=k-1){
                if(cnt.size()==k) max = Math.max(max, curr);
                curr -= nums[i-k+1];
                cnt.put(nums[i - k + 1], cnt.get(nums[i - k + 1]) - 1);
                if(cnt.get(nums[i - k + 1]) == 0) cnt.remove(nums[i - k + 1]);
            }
        }
        return max;
    }
}
```