Maximum Sum of Almost Unique Subarray - Problem
You're given an integer array nums and two positive integers m and k. Your task is to find the maximum sum among all subarrays of length k that contain at least m distinct elements.
A subarray is considered "almost unique" if it has at least m different values. If no such subarray exists, return 0.
Example: Given nums = [2,6,7,3,1,7], m = 3, k = 4
The subarray [2,6,7,3] has 4 distinct elements (≥ 3) and sum = 18
The subarray [6,7,3,1] has 4 distinct elements (≥ 3) and sum = 17
The subarray [7,3,1,7] has 3 distinct elements (≥ 3) and sum = 18
Maximum sum = 18
Input & Output
example_1.py — Basic Case
$
Input:
nums = [2,6,7,3,1,7], m = 3, k = 4
›
Output:
18
💡 Note:
The subarrays of length 4 are: [2,6,7,3] (4 distinct, sum=18), [6,7,3,1] (4 distinct, sum=17), [7,3,1,7] (3 distinct, sum=18). All have ≥3 distinct elements, maximum sum is 18.
example_2.py — No Valid Subarray
$
Input:
nums = [5,9,9,2,4,5,4], m = 1, k = 3
›
Output:
23
💡 Note:
All subarrays of length 3 have at least 1 distinct element. The maximum sum subarray is [9,9,5] with sum 23.
example_3.py — Edge Case
$
Input:
nums = [1,1,1,7,8,9], m = 3, k = 4
›
Output:
25
💡 Note:
Only the subarray [1,7,8,9] has at least 3 distinct elements, with sum 1+7+8+9=25.
Constraints
- 1 ≤ k ≤ nums.length ≤ 105
- 1 ≤ m ≤ k
- 1 ≤ nums[i] ≤ 105
- k is always less than or equal to the array length
- m is always less than or equal to k
Visualization
Tap to expand
Understanding the Visualization
1
Set up initial tasting menu
Start with first k dishes, count cuisine types and total price
2
Slide your tasting selection
Add next dish, remove first dish from your selection
3
Update tracking efficiently
Adjust cuisine count and total price incrementally
4
Check diversity requirement
If cuisine variety ≥ m, compare with best price found so far
Key Takeaway
🎯 Key Insight: The sliding window technique allows us to efficiently maintain both the sum and distinct count as we move through the array, avoiding the need to recalculate everything from scratch for each position. By using a frequency map, we can add/remove elements in O(1) time and track distinct elements accurately.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code