↓Skip to main content
  1. LeetCode/

LeetCode 2461: Maximum Sum of Distinct Subarrays With Length K

·2 mins· ·
LeetCode Medium Sliding-Window Hash-Table Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2025-12-24

  • Submissions: Accepted ×2

Approach
#

The same template as LeetCode 2841: a fixed window of length k with a sum and a count map. A distinct count equal to k means no duplicates in the window.

Another way, which both of my accepted versions used, is a variable window: shrink the left on a duplicate or when the window exceeds k, and update the answer when the length is exactly k.

My Solution
#

class Solution:
    def maximumSubarraySum(self, nums: List[int], k: int) -> int:
        cnt = Counter()
        window = best = 0
        for right, x in enumerate(nums):
            cnt[x] += 1
            window += x
            if right >= k:
                out = nums[right - k]
                cnt[out] -= 1
                window -= out
                if cnt[out] == 0:
                    del cnt[out]
            if right >= k - 1 and len(cnt) == k:   # all k values distinct
                best = max(best, window)
        return best

My second accepted version used a set with a variable window (lightly reordered here):

class Solution:
    def maximumSubarraySum(self, nums: List[int], k: int) -> int:
        seen = set()
        left = window = best = 0
        for right, x in enumerate(nums):
            while x in seen or right - left >= k:
                seen.remove(nums[left])
                window -= nums[left]
                left += 1
            seen.add(x)
            window += x
            if right - left + 1 == k:
                best = max(best, window)
        return best

Complexity
#

Time O(n), space O(k).

Mistakes to Avoid
#

  • Using len(cnt) >= k with a fixed window: a length-k window has at most k distinct values, so it must equal k.
  • With the variable window, finish shrinking before adding the new element to the set.

Interview Explanation
#

This is a fixed sliding window of length k with a sum and a count map, deleting keys at zero. The map’s size equals k exactly when everything in the window is distinct, and then I update the best sum. A set with a variable window also works: shrink the left on a duplicate or past length k. Time O(n).

Related

LeetCode 3679: Minimum Discards to Balance Inventory
·3 mins
LeetCode Medium Sliding-Window Hash-Table Simulation Counting Array
LeetCode 3679 note: the rule already decides what must be discarded, so simulate it; the length-w window counts only kept arrivals, and discarded ones must not be subtracted when they leave
LeetCode 2841: Maximum Sum of Almost Unique Subarray
·2 mins
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2841 note: a fixed window of length k keeps a sum and a count map; the number of distinct values is the map’s size, so delete keys that drop to zero
LeetCode 1248: Count Number of Nice Subarrays
·3 mins
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 1248 note: “exactly k odd numbers” is not monotonic, so compute “at most k” minus “at most k - 1”; or use prefix sums with a hash map
LeetCode 1423: Maximum Points You Can Obtain from Cards
·1 min
LeetCode Medium Sliding-Window Prefix-Sum Array
LeetCode 1423 note: taking k cards from the ends leaves a contiguous middle of n - k cards; find its minimum sum with a fixed-size window
LeetCode 1493: Longest Subarray of 1's After Deleting One Element
·2 mins
LeetCode Medium Sliding-Window Dynamic-Programming Array
LeetCode 1493 note: find the longest window with at most one 0; since one element must be deleted, the answer is the window length minus 1
LeetCode 594: Longest Harmonious Subsequence
·1 min
LeetCode Easy Array Hash-Table Sliding-Window Sorting
LeetCode 594 note: subsequences need not be contiguous, so just count; for each x add the counts of x and x + 1