Maximum Sum of Distinct Subarrays With Length K

MediumSliding Window · Hash Map🧩 Sliding WindowLeetCode #2461 ↗Updated

Problem

Given an integer array nums and a window size k, look at every contiguous subarray of length exactly k. Among those whose elements are all different, return the largest sum. If no such window exists, return 0.
Inputnums = [1,5,4,2,9,9,9], k = 3Output15 ([4,2,9])
Inputnums = [4,4,4], k = 3Output0
Inputnums = [3,1,3,2], k = 2Output5 ([3,2])

1 ≤ k ≤ n ≤ 105  ·  1 ≤ nums[i] ≤ 105  ·  answer may exceed 32-bit → return long

Try it yourself

Java
class Solution {
    public long maximumSubarraySum(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Consecutive windows differ by one element in and one element out. Keep a running sum and a frequency map: the window is all-distinct exactly when the map holds k distinct keys.
PatternSliding Window

Instinct Longest, shortest or count of contiguous subarrays/substrings meeting a rule? Grow a window on the right, shrink it on the left, never step back.

Memory hack Move like a caterpillar - the head stretches forward to grab, the tail pulls up only when the body breaks the rule.

Open the Sliding Window guide →

Approaches

Brute ForceRebuild Each Window

Time O(n · k)Space O(k)

For every start index, walk the next k elements, adding them to a fresh set and summing them. If a value repeats, the window is invalid; otherwise its sum is a candidate.

Java
public long maximumSubarraySum(int[] nums, int k) {
    long best = 0;
    for (int start = 0; start + k <= nums.length; start++) {
        Set<Integer> seen = new HashSet<>();
        long sum = 0;
        boolean distinct = true;
        for (int i = start; i < start + k; i++) {
            if (!seen.add(nums[i])) { // duplicate found
                distinct = false;
                break;
            }
            sum += nums[i];
        }
        if (distinct) best = Math.max(best, sum);
    }
    return best;
}

Straightforward, but re-scans overlapping windows — up to 1010 steps.

At a glance

LevelApproachTimeSpace
Brute ForceRebuild Each WindowO(n · k)O(k)
OptimalFixed Sliding Window + Frequency MapO(n)O(k)
Common pitfalls
  • Accumulating the sum in int — 105 × 105 overflows.
  • Decrementing a count without removing zero-count keys — size() becomes wrong.
  • Checking validity before the window has reached length k.
Interview tips
  • Name the trick: map size = number of distinct elements in the window.
  • Clarify that the answer is 0 (not -1) when no window qualifies.
  • Mention the array-instead-of-map optimisation given the bounded values.
Pattern
Fixed-size sliding window + counts → aggregate over every length-k window with a uniqueness or frequency condition.
My notes saved in this browser