Maximum Sum of Almost Unique Subarray - Problem

You are given an integer array nums and two positive integers m and k.

Return the maximum sum out of all almost unique subarrays of length k of nums. If no such subarray exists, return 0.

A subarray of nums is almost unique if it contains at least m distinct elements.

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,2,1,2,3], m = 2, k = 3
Output: 6
💡 Note: Check subarrays of length 3: [2,2,1] has 2 distinct (sum=5), [2,1,2] has 2 distinct (sum=5), [1,2,3] has 3 distinct (sum=6). Maximum is 6.
Example 2 — Not Enough Distinct
$ Input: nums = [1,1,1,7], m = 3, k = 2
Output: 0
💡 Note: All subarrays of length 2: [1,1] has 1 distinct, [1,1] has 1 distinct, [1,7] has 2 distinct. None have at least 3 distinct elements.
Example 3 — All Elements Distinct
$ Input: nums = [1,2,3,4], m = 2, k = 3
Output: 9
💡 Note: Subarrays: [1,2,3] has 3 distinct (sum=6), [2,3,4] has 3 distinct (sum=9). Maximum is 9.

Constraints

  • 1 ≤ k ≤ nums.length ≤ 104
  • 1 ≤ m ≤ k
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Maximum Sum of Almost Unique Subarraynums = [2,2,1,2,3], m = 2, k = 322123[2,2,1]: 2 distinct ≥ 2 ✓, sum = 5[2,1,2]: 2 distinct ≥ 2 ✓, sum = 5[1,2,3]: 3 distinct ≥ 2 ✓, sum = 6Maximum Sum: 6
Understanding the Visualization
1
Input
Array nums, minimum distinct count m, subarray length k
2
Process
Check each subarray of length k for distinct element count
3
Output
Maximum sum among valid subarrays
Key Takeaway
🎯 Key Insight: Use sliding window with frequency map to efficiently track distinct elements in each subarray
Asked in
Amazon 15 Google 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
456 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