Maximum Sum of Distinct Subarrays With Length K (LeetCode 2461): Solution and Explanation

Medium
Array
Hash Table
Sliding Window

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

  1. Create an empty map count, and set window = 0, best = 0.
  2. For each right, add one to count[nums[right]] and add nums[right] to window.
  3. If right >= k, the value nums[right - k] slides out: subtract one from its count, delete the key at 0, and subtract the value from window.
  4. If right >= k - 1 and len(count) == k, set best = max(best, window).
  5. Return best.

Step-by-step example

nums = [1,5,4,2,9,9,9], k = 3
  1. The first window [1,5,4] has three keys and sum 10, so best = 10.
  2. Slide: 1 leaves, 2 enters. [5,4,2] has three keys and sum 11, so best = 11.
  3. Slide: 5 leaves, 9 enters. [4,2,9] has three keys and sum 15, so best = 15.
  4. 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 best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index enters and leaves the window once, and every map operation is O(1) on average.

Space

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.