Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: nums = [2,6,7,3,1,7], m = 3, k = 4
Output: 18
Explanation: There are 3 almost unique subarrays of size k = 4. These subarrays are [2, 6, 7, 3], [6, 7, 3, 1], and [7, 3, 1, 7]. Among these subarrays, the one with the maximum sum is [2, 6, 7, 3] which has a sum of 18.
Example 2:
Input: nums = [5,9,9,2,4,5,4], m = 1, k = 3 Output: 23 Explanation: There are 5 almost unique subarrays of size k. These subarrays are [5, 9, 9], [9, 9, 2], [9, 2, 4], [2, 4, 5], and [4, 5, 4]. Among these subarrays, the one with the maximum sum is [5, 9, 9] which has a sum of 23.
Example 3:
Input: nums = [1,2,1,2,1,2,1], m = 3, k = 3 Output: 0 Explanation: There are no subarrays of sizek = 3that contain at leastm = 3distinct elements in the given array [1,2,1,2,1,2,1]. Therefore, no almost unique subarrays exist, and the maximum sum is 0.
Constraints:
1 <= nums.length <= 2 * 1041 <= m <= k <= nums.length1 <= nums[i] <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Sliding Window
[2,6,7,3,1,7] 3 4
[5,9,9,2,4,5,4] 1 3
[1,2,1,2,1,2,1] 3 3
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2841: Maximum Sum of Almost Unique Subarray
class Solution {
public long maxSum(List<Integer> nums, int m, int k) {
Map<Integer, Integer> cnt = new HashMap<>();
int n = nums.size();
long s = 0;
for (int i = 0; i < k; ++i) {
cnt.merge(nums.get(i), 1, Integer::sum);
s += nums.get(i);
}
long ans = cnt.size() >= m ? s : 0;
for (int i = k; i < n; ++i) {
cnt.merge(nums.get(i), 1, Integer::sum);
if (cnt.merge(nums.get(i - k), -1, Integer::sum) == 0) {
cnt.remove(nums.get(i - k));
}
s += nums.get(i) - nums.get(i - k);
if (cnt.size() >= m) {
ans = Math.max(ans, s);
}
}
return ans;
}
}
// Accepted solution for LeetCode #2841: Maximum Sum of Almost Unique Subarray
func maxSum(nums []int, m int, k int) int64 {
cnt := map[int]int{}
var s int64
for _, x := range nums[:k] {
cnt[x]++
s += int64(x)
}
var ans int64
if len(cnt) >= m {
ans = s
}
for i := k; i < len(nums); i++ {
cnt[nums[i]]++
cnt[nums[i-k]]--
if cnt[nums[i-k]] == 0 {
delete(cnt, nums[i-k])
}
s += int64(nums[i]) - int64(nums[i-k])
if len(cnt) >= m {
ans = max(ans, s)
}
}
return ans
}
# Accepted solution for LeetCode #2841: Maximum Sum of Almost Unique Subarray
class Solution:
def maxSum(self, nums: List[int], m: int, k: int) -> int:
cnt = Counter(nums[:k])
s = sum(nums[:k])
ans = s if len(cnt) >= m else 0
for i in range(k, len(nums)):
cnt[nums[i]] += 1
cnt[nums[i - k]] -= 1
s += nums[i] - nums[i - k]
if cnt[nums[i - k]] == 0:
cnt.pop(nums[i - k])
if len(cnt) >= m:
ans = max(ans, s)
return ans
// Accepted solution for LeetCode #2841: Maximum Sum of Almost Unique Subarray
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2841: Maximum Sum of Almost Unique Subarray
// class Solution {
// public long maxSum(List<Integer> nums, int m, int k) {
// Map<Integer, Integer> cnt = new HashMap<>();
// int n = nums.size();
// long s = 0;
// for (int i = 0; i < k; ++i) {
// cnt.merge(nums.get(i), 1, Integer::sum);
// s += nums.get(i);
// }
// long ans = cnt.size() >= m ? s : 0;
// for (int i = k; i < n; ++i) {
// cnt.merge(nums.get(i), 1, Integer::sum);
// if (cnt.merge(nums.get(i - k), -1, Integer::sum) == 0) {
// cnt.remove(nums.get(i - k));
// }
// s += nums.get(i) - nums.get(i - k);
// if (cnt.size() >= m) {
// ans = Math.max(ans, s);
// }
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2841: Maximum Sum of Almost Unique Subarray
function maxSum(nums: number[], m: number, k: number): number {
const n = nums.length;
const cnt: Map<number, number> = new Map();
let s = 0;
for (let i = 0; i < k; ++i) {
cnt.set(nums[i], (cnt.get(nums[i]) || 0) + 1);
s += nums[i];
}
let ans = cnt.size >= m ? s : 0;
for (let i = k; i < n; ++i) {
cnt.set(nums[i], (cnt.get(nums[i]) || 0) + 1);
cnt.set(nums[i - k], cnt.get(nums[i - k])! - 1);
if (cnt.get(nums[i - k]) === 0) {
cnt.delete(nums[i - k]);
}
s += nums[i] - nums[i - k];
if (cnt.size >= m) {
ans = Math.max(ans, s);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.