Maximum Sum of Distinct Subarrays With Length K - Problem

You're given an integer array nums and an integer k. Your task is to find the maximum sum among all subarrays that satisfy two important conditions:

  1. The subarray has exactly k elements
  2. All elements in the subarray are distinct (no duplicates)

If no such subarray exists, return 0.

Note: A subarray is a contiguous sequence of elements within an array.

Example: For nums = [1,5,4,2,9,9,9] and k = 3, the subarray [5,4,2] has sum 11 and all distinct elements, making it a valid candidate.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1,5,4,2,9,9,9], k = 3
โ€บ Output: 15
๐Ÿ’ก Note: The subarray [4,2,9] has all distinct elements and sum 15, which is the maximum possible.
example_2.py โ€” All Same Elements
$ Input: nums = [4,4,4], k = 3
โ€บ Output: 0
๐Ÿ’ก Note: No subarray of length 3 has all distinct elements, so return 0.
example_3.py โ€” Small Array
$ Input: nums = [1,2], k = 3
โ€บ Output: 0
๐Ÿ’ก Note: Array length is less than k, so no valid subarray exists.

Constraints

  • 1 โ‰ค k โ‰ค nums.length โ‰ค 105
  • -104 โ‰ค nums[i] โ‰ค 104
  • All subarrays must have exactly k elements
  • All elements in valid subarrays must be distinct

Visualization

Tap to expand
๐ŸŽฌ Movie Theater Window ManagementTheater Seats (Array Elements)ID:1ID:5ID:4ID:2ID:9ID:9Window 1 (k=3)Window 2 (sliding)๐Ÿ“Š Window AnalyticsWindow 1:โ€ข IDs: {1, 5, 4} โœ“ All uniqueโ€ข Revenue: $10Window 2:๐Ÿ”„ Sliding Process1. Remove leftmost customer (ID:1)2. Add new customer (ID:2)3. Update frequency map: {5:1, 4:1, 2:1}4. Check: 3 unique IDs = k โœ“ Valid window!๐ŸŽฏ Key Insight: Hash Map Magicโ€ข O(1) time to add/remove elements from frequency mapโ€ข Map size tells us if all elements are distinct: size == k means valid window
Understanding the Visualization
1
Initialize Window
Start with the first k seats, count frequencies and calculate total revenue
2
Slide Right
Add new customer on right, remove customer on left
3
Update Tracking
Update frequency map and total sum efficiently
4
Check Validity
If all k customers have unique IDs, compare with maximum revenue
Key Takeaway
๐ŸŽฏ Key Insight: The sliding window with hash map approach achieves optimal O(n) time by maintaining both the sum and distinctness check efficiently as we move through the array, processing each element exactly once.
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 22
52.0K Views
High Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen