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 With Length K INPUT nums array: 1 2 1 2 6 7 5 1 0 1 2 3 4 5 6 7 k = 3 Find max sum of subarrays with: - Length = k (3 elements) - All distinct elements Window size k=3: [_, _, _] ALGORITHM STEPS 1 Initialize Window Create freq map, sum=0 2 Build First Window Add first k elements 3 Slide Window Remove left, add right 4 Check Distinct Update max if all unique Window Sliding Process: [1,2,1] dup! [2,1,2] dup! [1,2,6] 9 [2,6,7] 15 [6,7,5] 18 FINAL RESULT Best window found: 1 2 1 2 6 7 5 1 indices 4,5,6 Calculation: 6 + 7 + 5 = 18 Output: 18 OK - All elements {6,7,5} are distinct! Key Insight: Use a HashMap to track element frequencies in the current window. When sliding: 1) Remove leftmost element (decrement count, delete if zero) 2) Add new right element. If map size equals k, all elements are distinct --> update max sum. TutorialsPoint - Maximum Sum of Distinct Subarrays With Length K | Optimized Sliding Window with Frequency Map Time: O(n) | Space: O(k)
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