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.
Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 2 Output: 2 Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).
Example 2:
Input: nums = [-1,3,5,1,4,2,-9], target = 6 Output: 2 Explanation: There are 3 subarrays with sum equal to 6. ([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.
Constraints:
1 <= nums.length <= 105-104 <= nums[i] <= 1040 <= target <= 106Problem summary: Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Greedy
[1,1,1,1,1] 2
[-1,3,5,1,4,2,-9] 6
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1546: Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
class Solution {
public int maxNonOverlapping(int[] nums, int target) {
int ans = 0, n = nums.length;
for (int i = 0; i < n; ++i) {
Set<Integer> vis = new HashSet<>();
int s = 0;
vis.add(0);
while (i < n) {
s += nums[i];
if (vis.contains(s - target)) {
++ans;
break;
}
++i;
vis.add(s);
}
}
return ans;
}
}
// Accepted solution for LeetCode #1546: Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
func maxNonOverlapping(nums []int, target int) (ans int) {
n := len(nums)
for i := 0; i < n; i++ {
s := 0
vis := map[int]bool{0: true}
for ; i < n; i++ {
s += nums[i]
if vis[s-target] {
ans++
break
}
vis[s] = true
}
}
return
}
# Accepted solution for LeetCode #1546: Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
ans = 0
i, n = 0, len(nums)
while i < n:
s = 0
vis = {0}
while i < n:
s += nums[i]
if s - target in vis:
ans += 1
break
i += 1
vis.add(s)
i += 1
return ans
// Accepted solution for LeetCode #1546: Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
struct Solution;
use std::collections::HashMap;
impl Solution {
fn max_non_overlapping(nums: Vec<i32>, target: i32) -> i32 {
let mut sum = 0;
let mut hm: HashMap<i32, usize> = HashMap::new();
let mut last = 0;
hm.insert(0, 0);
let n = nums.len();
let mut res = 0;
for i in 0..n {
let x = nums[i];
sum += x;
if let Some(&j) = hm.get(&(sum - target)) {
if j >= last {
res += 1;
last = i + 1;
}
}
*hm.entry(sum).or_default() = i + 1;
}
res
}
}
#[test]
fn test() {
let nums = vec![1, 1, 1, 1, 1];
let target = 2;
let res = 2;
assert_eq!(Solution::max_non_overlapping(nums, target), res);
let nums = vec![-1, 3, 5, 1, 4, 2, -9];
let target = 6;
let res = 2;
assert_eq!(Solution::max_non_overlapping(nums, target), res);
let nums = vec![-2, 6, 6, 3, 5, 4, 1, 2, 8];
let target = 10;
let res = 3;
assert_eq!(Solution::max_non_overlapping(nums, target), res);
let nums = vec![0, 0, 0];
let target = 0;
let res = 3;
assert_eq!(Solution::max_non_overlapping(nums, target), res);
}
// Accepted solution for LeetCode #1546: Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
function maxNonOverlapping(nums: number[], target: number): number {
const n = nums.length;
let ans = 0;
for (let i = 0; i < n; ++i) {
let s = 0;
const vis: Set<number> = new Set();
vis.add(0);
for (; i < n; ++i) {
s += nums[i];
if (vis.has(s - target)) {
++ans;
break;
}
vis.add(s);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
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: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.