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 an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:
k, andReturn 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.
Example 1:
Input: nums = [1,5,4,2,9,9,9], k = 3 Output: 15 Explanation: The subarrays of nums with length 3 are: - [1,5,4] which meets the requirements and has a sum of 10. - [5,4,2] which meets the requirements and has a sum of 11. - [4,2,9] which meets the requirements and has a sum of 15. - [2,9,9] which does not meet the requirements because the element 9 is repeated. - [9,9,9] which does not meet the requirements because the element 9 is repeated. We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions
Example 2:
Input: nums = [4,4,4], k = 3 Output: 0 Explanation: The subarrays of nums with length 3 are: - [4,4,4] which does not meet the requirements because the element 4 is repeated. We return 0 because no subarrays meet the conditions.
Constraints:
1 <= k <= nums.length <= 1051 <= nums[i] <= 105Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Sliding Window
[1,5,4,2,9,9,9] 3
[4,4,4] 3
max-consecutive-ones-iii)longest-nice-subarray)optimal-partition-of-string)count-the-number-of-good-subarrays)maximum-good-subarray-sum)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2461: Maximum Sum of Distinct Subarrays With Length K
class Solution {
public long maximumSubarraySum(int[] nums, int k) {
int n = nums.length;
Map<Integer, Integer> cnt = new HashMap<>(k);
long s = 0;
for (int i = 0; i < k; ++i) {
cnt.merge(nums[i], 1, Integer::sum);
s += nums[i];
}
long ans = cnt.size() == k ? s : 0;
for (int i = k; i < n; ++i) {
cnt.merge(nums[i], 1, Integer::sum);
if (cnt.merge(nums[i - k], -1, Integer::sum) == 0) {
cnt.remove(nums[i - k]);
}
s += nums[i] - nums[i - k];
if (cnt.size() == k) {
ans = Math.max(ans, s);
}
}
return ans;
}
}
// Accepted solution for LeetCode #2461: Maximum Sum of Distinct Subarrays With Length K
func maximumSubarraySum(nums []int, k int) (ans int64) {
n := len(nums)
cnt := map[int]int64{}
var s int64
for _, x := range nums[:k] {
cnt[x]++
s += int64(x)
}
if len(cnt) == k {
ans = s
}
for i := k; i < n; i++ {
cnt[nums[i]]++
cnt[nums[i-k]]--
if cnt[nums[i-k]] == 0 {
delete(cnt, nums[i-k])
}
s += int64(nums[i] - nums[i-k])
if len(cnt) == k && ans < s {
ans = s
}
}
return
}
# Accepted solution for LeetCode #2461: Maximum Sum of Distinct Subarrays With Length K
class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
cnt = Counter(nums[:k])
s = sum(nums[:k])
ans = s if len(cnt) == k else 0
for i in range(k, len(nums)):
cnt[nums[i]] += 1
cnt[nums[i - k]] -= 1
if cnt[nums[i - k]] == 0:
cnt.pop(nums[i - k])
s += nums[i] - nums[i - k]
if len(cnt) == k:
ans = max(ans, s)
return ans
// Accepted solution for LeetCode #2461: Maximum Sum of Distinct Subarrays With Length K
// 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 #2461: Maximum Sum of Distinct Subarrays With Length K
// class Solution {
// public long maximumSubarraySum(int[] nums, int k) {
// int n = nums.length;
// Map<Integer, Integer> cnt = new HashMap<>(k);
// long s = 0;
// for (int i = 0; i < k; ++i) {
// cnt.merge(nums[i], 1, Integer::sum);
// s += nums[i];
// }
// long ans = cnt.size() == k ? s : 0;
// for (int i = k; i < n; ++i) {
// cnt.merge(nums[i], 1, Integer::sum);
// if (cnt.merge(nums[i - k], -1, Integer::sum) == 0) {
// cnt.remove(nums[i - k]);
// }
// s += nums[i] - nums[i - k];
// if (cnt.size() == k) {
// ans = Math.max(ans, s);
// }
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2461: Maximum Sum of Distinct Subarrays With Length K
function maximumSubarraySum(nums: 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 === k ? 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 === k) {
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.