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 Subarray INPUT nums array: 2 i=0 2 i=1 1 i=2 2 i=3 3 i=4 Parameters: m = 2 (min distinct) k = 3 (window size) All k=3 Subarrays: [2,2,1] sum=5 [2,1,2] sum=5 [1,2,3] sum=6 Need at least m=2 distinct elements in each subarray ALGORITHM STEPS 1 Init Hash Map Track element counts in sliding window 2 Build First Window Add first k elements Calculate initial sum 3 Slide Window Remove left, add right Update hash map counts 4 Check & Update Max If distinct >= m, update max sum Hash Map for [1,2,3]: 1: 1 2: 1 3: 1 Distinct = 3 >= 2 [OK] FINAL RESULT Best Almost Unique Subarray: 1 2 3 indices [2, 3, 4] Sum Calculation: 1 + 2 + 3 = 6 3 distinct elements OUTPUT 6 Maximum sum found [OK] All subarrays checked Key Insight: Use a sliding window with a hash map to track element frequencies. The hash map's size gives the count of distinct elements. When distinct count >= m, the subarray is "almost unique". Update max sum only for valid subarrays. Time: O(n), Space: O(k) for the hash map. TutorialsPoint - Maximum Sum of Almost Unique Subarray | Hash Map Approach
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