Maximum Sum of Distinct Subarrays With Length K (LeetCode 2461): Solution and Explanation
Among all subarrays of length k with no repeated value, return the largest sum, or 0 if none exists.
Intuition
There are only n - k + 1 windows of length k, and each one differs from the previous by one value leaving on the left and one entering on the right. Recomputing each window from scratch would cost O(n * k); updating it costs O(1).
The sum is easy to update: add the new value and subtract the old one.
Distinctness needs a little more. Keep a hash map from value to how many times it appears in the window. Remove a key when its count drops to 0, so the map only holds values that are present.
A window of k slots is all distinct exactly when the map has k keys. Any repeat makes two slots share one key, so the key count falls below k.
Approach: Fixed-size sliding window with a count map
- Create an empty map
count, and setwindow = 0,best = 0. - For each
right, add one tocount[nums[right]]and addnums[right]towindow. - If
right >= k, the valuenums[right - k]slides out: subtract one from its count, delete the key at 0, and subtract the value fromwindow. - If
right >= k - 1andlen(count) == k, setbest = max(best, window). - Return
best.
Step-by-step example
nums = [1,5,4,2,9,9,9], k = 3
- The first window [1,5,4] has three keys and sum 10, so
best = 10. - Slide: 1 leaves, 2 enters. [5,4,2] has three keys and sum 11, so
best = 11. - Slide: 5 leaves, 9 enters. [4,2,9] has three keys and sum 15, so
best = 15. - Slide: [2,9,9] has count[9] = 2, so only two keys. Slide again: [9,9,9] has one key. Neither counts, and the answer is 15.
Code: Python, Java, C++
1class Solution:
2 def maximumSubarraySum(self, nums: List[int], k: int) -> int:
3 count = {}
4 window = 0
5 best = 0
6 for right in range(len(nums)):
7 count[nums[right]] = count.get(nums[right], 0) + 1
8 window += nums[right]
9 if right >= k:
10 old = nums[right - k]
11 count[old] -= 1
12 if count[old] == 0:
13 del count[old]
14 window -= old
15 if right >= k - 1 and len(count) == k:
16 best = max(best, window)
17 return best1class Solution {
2 public int maximumSubarraySum(int[] nums, int k) {
3 Map<Integer, Integer> count = new HashMap<>();
4 int window = 0, best = 0;
5 for (int right = 0; right < nums.length; right++) {
6 count.merge(nums[right], 1, Integer::sum);
7 window += nums[right];
8 if (right >= k) {
9 int old = nums[right - k];
10 if (count.merge(old, -1, Integer::sum) == 0) {
11 count.remove(old);
12 }
13 window -= old;
14 }
15 if (right >= k - 1 && count.size() == k) {
16 best = Math.max(best, window);
17 }
18 }
19 return best;
20 }
21}1class Solution {
2public:
3 int maximumSubarraySum(vector<int>& nums, int k) {
4 unordered_map<int, int> count;
5 int window = 0, best = 0;
6 for (int right = 0; right < (int)nums.size(); right++) {
7 count[nums[right]]++;
8 window += nums[right];
9 if (right >= k) {
10 int old = nums[right - k];
11 if (--count[old] == 0) {
12 count.erase(old);
13 }
14 window -= old;
15 }
16 if (right >= k - 1 && (int)count.size() == k) {
17 best = max(best, window);
18 }
19 }
20 return best;
21 }
22};Time and space complexity
O(n)
Each index enters and leaves the window once, and every map operation is O(1) on average.
O(k)
The map never holds more than k keys, one per value in the window.
Other approaches
Last-seen index (time O(n), space O(n))
Track the last index where each value appeared and the latest start that avoids any repeat. A window ending at right is distinct when that start is at most right - k + 1. Uses the same O(n) time with a map from value to index.
Variable window then trim (time O(n), space O(k))
Grow the window and shrink it from the left whenever a duplicate enters or the size passes k. Whenever the size is exactly k, the window is distinct and its sum is a candidate.
Check every window (time O(n * k), space O(k))
Build a set and a sum for each of the n - k + 1 windows separately. Simple, but O(n * k).
Common mistakes
- Leaving keys with count 0 in the map, which makes the key count larger than the number of distinct values present.
- Checking distinctness before the window is full, when the map naturally has fewer than k keys.
- Returning the largest window sum overall instead of only among distinct windows.
- Overflow: on LeetCode the sum can reach 10^10 and needs a 64-bit integer. The tests here keep it within 32 bits.
Frequently asked questions
Why does the key count prove the window is distinct?
The window has k slots. If every value is different, there are k keys. If any value repeats, two slots share a key, so the map has fewer than k keys.
Can I use a set instead of a count map?
Not directly. When a value leaves, a set cannot tell whether another copy is still inside the window. The count tells you when the last copy is gone.
What is returned when no window qualifies?
0. Every value is at least 1, so any valid window has a positive sum, and 0 safely means none was found.