Maximum Sum of Distinct Subarrays With Length K - Problem

You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:

  • The length of the subarray is k, and
  • All the elements of the subarray are distinct.

Return the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return 0.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1,2,6,7,5,1], k = 3
Output: 18
💡 Note: The subarray [6,7,5] has distinct elements and sum = 6 + 7 + 5 = 18, which is maximum among all valid subarrays.
Example 2 — No Valid Subarray
$ Input: nums = [1,2,1,2,1,2,1], k = 3
Output: 0
💡 Note: Every 3-length subarray contains duplicate elements (like [1,2,1]), so no valid distinct subarray exists.
Example 3 — Single Valid Window
$ Input: nums = [4,4,4], k = 3
Output: 0
💡 Note: The only subarray [4,4,4] has duplicate elements, so return 0.

Constraints

  • 1 ≤ k ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Maximum Sum of Distinct Subarrays (k=3)12126751Distinct Subarray: [6,7,5]Invalid Windows[1,2,1], [2,1,2], [1,2,6], [2,6,7]Valid Window[6,7,5] → Sum = 18Invalid Windows[7,5,1], [5,1,...]k = 3 elementsMaximum Sum: 18Only subarray [6,7,5] has all distinct elements
Understanding the Visualization
1
Input Array
Array [1,2,1,2,6,7,5,1] with k=3
2
Find Distinct Windows
Check each 3-length subarray for distinct elements
3
Maximum Sum
Return highest sum from valid windows: 18
Key Takeaway
🎯 Key Insight: Use sliding window with frequency map to efficiently track distinct elements while maintaining running sum
Asked in
Amazon 45 Google 38 Microsoft 32 Facebook 28
42.2K Views
Medium Frequency
~15 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