FAANGPrep Sprint
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.
