Home
DSA Patterns
Sliding Window
Maximum Sum of Distinct Subarrays With Length K
Maximum Sum of Distinct Subarrays With Length K
Maximum Sum of Distinct Subarrays With Length K: find the maximum sum of a fixed-size subarray where all elements are distinct.
Problem Understanding
Look at every contiguous window of exactly k elements in the integer array nums. Among the windows whose values are all distinct, with no value repeated, return the largest sum.
If every window of length k contains a duplicate, the answer is 0.
Algorithm Strategy
A brute force check for distinctness takes O(k). Doing this for every window results in O(Nk) or O(Nk^2). We need O(N).
Strategy: Fixed Sliding Window + Frequency Map
- Window: Maintain a window of size
k. - Tracking: Use a Hash Map (or frequency array) to count occurrences of each number in the current window.
- Validity: A full window is distinct exactly when the map holds
kdifferent keys (len(counts) == k).- If
count[num] > 1, we have a duplicate.
- If
- Updates:
- Add incoming element: Add it to the sum and increment its count.
- Remove outgoing element: Subtract it from the sum, decrement its count, and delete the key when the count reaches 0.
- If the window holds
kelements and the map holdskkeys, updatemax_sum.
Visual Walkthrough
WINDOW OF 3 DIFFERENT VALUES
EMPTY WINDOW
0
1
2
3
4
5
6
Sum
0
Distinct
0
Best
0
counts (value:times)
Empty
Best 0, sum 0, no counts. A window must hold 3 different values to count
Next
Add nums[0] = 1: sum 1, count of 1 is 1
Array
k
Watch the window slide: a solid frame marks a full window of different values, and a dashed frame marks one that repeats a value. The counts beside the figure show which value repeats.
Dry Run: [1, 5, 4, 2, 9, 9, 9], k=3
| Window (Indices) | Elements | Map State | Distinct? | Sum | Max |
|---|---|---|---|---|---|
[0, 2] |
[1, 5, 4] |
{1:1, 5:1, 4:1} |
✅ Yes | 10 | 10 |
[1, 3] |
[5, 4, 2] |
{5:1, 4:1, 2:1} |
✅ Yes | 11 | 11 |
[2, 4] |
[4, 2, 9] |
{4:1, 2:1, 9:1} |
✅ Yes | 15 | 15 |
[3, 5] |
[2, 9, 9] |
{2:1, 9:2} |
❌ No (9 is dup) | - | 15 |
[4, 6] |
[9, 9, 9] |
{9:3} |
❌ No | - | 15 |
| Result | 15 |
Edge Cases & Common Mistakes
Edge Cases:
- No distinct window: Return 0, e.g.
nums = [4, 4, 4],k = 3. - k = 1: Every single element is distinct, so the answer is the largest element.
- k = n: There is one window; it counts only if all
nvalues differ.
Common Mistakes:
- Forgetting to delete zero counts: A key left at count 0 keeps the map size too large, so a distinct window is never recognised.
- Comparing before the window is full: Only windows of exactly
kelements count. - Integer overflow: Sums reach
10^5 × 10^5; use a 64-bit type.
Code Solution
Efficient implementation using a Frequency Map.
Maximum Sum of Distinct Subarrays With Length K Code
1var maximumSubarraySum = function(nums, k) {2 let maxSum = 0;3 let currentSum = 0;4 let counts = new Map();56 for (let i = 0; i < nums.length; i++) {7 currentSum += nums[i];8 counts.set(nums[i], (counts.get(nums[i]) || 0) + 1);910 if (i >= k) {11 let out = nums[i - k];12 currentSum -= out;13 counts.set(out, counts.get(out) - 1);14 if (counts.get(out) === 0) counts.delete(out);15 }1617 if (i >= k - 1) {18 if (counts.size === k) {19 maxSum = Math.max(maxSum, currentSum);20 }21 }22 }23 return maxSum;24};
Maximum Sum of Distinct Subarrays With Length K in Python, Java, C++, TypeScript and C
Maximum Sum of Distinct Subarrays With Length K in Python
def maximumSubarraySum(nums: List[int], k: int) -> int:
max_sum = 0
current_sum = 0
counts = {}
for i in range(len(nums)):
current_sum += nums[i]
counts[nums[i]] = counts.get(nums[i], 0) + 1
if i >= k:
out = nums[i - k]
current_sum -= out
counts[out] -= 1
if counts[out] == 0:
del counts[out]
if i >= k - 1:
if len(counts) == k:
max_sum = max(max_sum, current_sum)
return max_sumMaximum Sum of Distinct Subarrays With Length K in Java
public long maximumSubarraySum(int[] nums, int k) {
long maxSum = 0;
long currentSum = 0;
Map<Integer, Integer> counts = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
currentSum += nums[i];
counts.put(nums[i], counts.getOrDefault(nums[i], 0) + 1);
if (i >= k) {
int out = nums[i - k];
currentSum -= out;
counts.put(out, counts.get(out) - 1);
if (counts.get(out) == 0) counts.remove(out);
}
if (i >= k - 1) {
if (counts.size() == k) {
maxSum = Math.max(maxSum, currentSum);
}
}
}
return maxSum;
}Maximum Sum of Distinct Subarrays With Length K in C++
class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
long long maxSum = 0;
long long currentSum = 0;
unordered_map<int, int> counts;
for (int i = 0; i < (int) nums.size(); i++) {
currentSum += nums[i];
counts[nums[i]]++;
if (i >= k) {
int out = nums[i - k];
currentSum -= out;
if (--counts[out] == 0) counts.erase(out);
}
if (i >= k - 1) {
if ((int) counts.size() == k) {
maxSum = max(maxSum, currentSum);
}
}
}
return maxSum;
}
};Maximum Sum of Distinct Subarrays With Length K in TypeScript
function maximumSubarraySum(nums: number[], k: number): number {
let maxSum = 0;
let currentSum = 0;
const counts = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
currentSum += nums[i];
counts.set(nums[i], (counts.get(nums[i]) ?? 0) + 1);
if (i >= k) {
const out = nums[i - k];
currentSum -= out;
counts.set(out, counts.get(out)! - 1);
if (counts.get(out) === 0) counts.delete(out);
}
if (i >= k - 1) {
if (counts.size === k) {
maxSum = Math.max(maxSum, currentSum);
}
}
}
return maxSum;
}Maximum Sum of Distinct Subarrays With Length K in C
long long maximumSubarraySum(int* nums, int numsSize, int k) {
int* counts = calloc(100001, sizeof(int)); // 1 <= nums[i] <= 10^5
int distinct = 0;
long long maxSum = 0;
long long currentSum = 0;
for (int i = 0; i < numsSize; i++) {
currentSum += nums[i];
if (counts[nums[i]]++ == 0) distinct++;
if (i >= k) {
int out = nums[i - k];
currentSum -= out;
if (--counts[out] == 0) distinct--;
}
if (i >= k - 1) {
if (distinct == k) {
maxSum = currentSum > maxSum ? currentSum : maxSum;
}
}
}
free(counts);
return maxSum;
}More practice: DSA interview questions with answers · patterns cheat sheet
