Maximum Sum of Distinct Subarrays With Length K
Problem Statement
You are given an integer array nums and a number k.
Look at every contiguous block of exactly k elements. A block only counts if all k of its values are different (no value appears twice in it).
Return the largest sum among the blocks that count. If no block counts, return 0.
An integer array nums of length n, and an integer k.
A 64-bit integer: the maximum sum of a length-k subarray with all distinct values, or 0 if there is none.
The size-3 blocks are [1,5,4]=10, [5,4,2]=11, [4,2,9]=15, [2,9,9] and [9,9,9]. The last two repeat 9, so they don't count. The best of the rest is 15.
The only block, [4,4,4], has repeated values, so nothing counts and the answer is 0.
- • 1 ≤ k ≤ nums.length ≤ 10^5
- • 1 ≤ nums[i] ≤ 10^5
- • A window sum can reach 10^10, which does not fit in a 32-bit int.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each window, use a fresh set to test distinctness and sum it
Slide sum and value counts together; a full window counts when distinct == k
For every start index, walk through the k elements of that window with a fresh hash set. If a value is already in the set, the window has a repeat and doesn't count. Otherwise add up the values and compare with the best.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.