Browse curriculum

FAANGPrep Sprint

Maximum Sum of Distinct Subarrays With Length K

Find the maximum sum of a fixed-size subarray where all elements are distinct.

Medium
20 min
Solve on LeetCode

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

  1. Window: Maintain a window of size k.
  2. Tracking: Use a Hash Map (or frequency array) to count occurrences of each number in the current window.
  3. Validity: A full window is distinct exactly when the map holds k different keys (len(counts) == k).
    • If count[num] > 1, we have a duplicate.
  4. 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 k elements and the map holds k keys, update max_sum.

Visual Walkthrough

WINDOW OF 3 DIFFERENT VALUES

EMPTY WINDOW

1

0

5

1

4

2

2

3

9

4

9

5

9

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

3

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.