Python 1546.py
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
result = 0
have = set([ 0 ])
total = 0
for n in nums:
# prefix sum
total += n
if total - target in have:
result += 1
have.clear()
have.add(total)
return result
Difficulty
and has an acceptance rate of about 49% (70k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Hash Table
- Prefix Sum
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The routine computes the maximum count of non-overlapping contiguous sub-segments whose elements sum to a given target. It processes the input array in a single pass, using a running prefix sum and a hash-based container to detect when a segment ending at the current position fulfills the required sum. Whenever such a segment is found, the count is increased and the state is reset so that subsequent segments cannot overlap the one just accepted.
Key Steps
Initialization
At the start the algorithm prepares three variables: a counter for successful segments, a set that stores prefix sums observed so far, and an accumulator for the running total. The set is seeded with zero to represent the empty prefix before any element is processed.
result = 0
have = set([0])
total = 0
Iteration and Prefix Sum
The core loop walks through each element of the input list. For each element the running total is updated, thereby maintaining the prefix sum up to the current index.
for n in nums:
total += n
Detection of Target Subarray
After the prefix sum is updated, the algorithm checks whether a previous prefix sum exists such that the difference between the current total and that previous sum equals the target. This condition is expressed as total - target in have. If it holds, a sub-array ending at the current position sums to the target.
if total - target in have:
Resetting State After a Match
When a qualifying sub-array is identified, the result counter is incremented. The set of stored prefix sums is cleared because any prefix recorded before the current index would belong to the just-found segment and therefore must not be reused for overlapping segments.
result += 1
have.clear()
Maintaining Prefix Set
Regardless of whether a match was found, the current prefix sum is added to the set. This ensures that future indices can reference the most recent cumulative total when checking for new target-summing sub-arrays.
have.add(total)
Final Result
After the loop finishes, the accumulated count is returned as the maximum number of non-overlapping sub-arrays that meet the target sum.
return result
Edge Cases Handled
The algorithm gracefully handles an empty input list because the loop body is never executed, leaving the result at its initial value of zero. When the target value is zero, the presence of the initial zero in the prefix set enables immediate detection of any prefix that also sums to zero, correctly counting such segments. Negative numbers are accommodated because the prefix sum and the set operations are agnostic to sign; the subtraction total - target works uniformly for positive, zero, or negative targets. Repeated prefix sums that arise from sequences of zeros or balanced positive-negative pairs are stored only once in the set, preventing redundant checks while still allowing detection of distinct qualifying sub-arrays. The clearing of the set after each successful detection guarantees that overlapping intervals are never counted, even when multiple overlapping candidates exist in the raw data.
Performance Optimizations
The use of a hash set for storing previously seen prefix sums provides constant-time membership tests, allowing the algorithm to decide instantly whether a target-summing sub-array ends at the current index. By clearing the set immediately after a successful match, the implementation discards all prefix sums that could lead to overlapping intervals, thereby limiting the size of the set to the number of elements processed since the last match. This bounded growth reduces memory pressure compared to approaches that retain the entire history of prefix sums. The algorithm avoids auxiliary arrays or nested loops, achieving its goal with a single linear traversal and minimal auxiliary state.
ELI5 - Simplified Explanation
Imagine a long train track where each train car has a number written on it. The goal is to find groups of cars sitting right next to each other that add up to a specific target number.
The code starts by walking along the track one car at a time. As it moves, it keeps a running count of all the numbers it has seen so far. Think of this like keeping a tally in a notepad. It stores all these past tallies in a special collection so it can check them later.
When it sees a new car, it adds that number to the running total. Then it asks a question: if the current total minus the target is already in the notepad, that means there is a hidden group of cars somewhere behind the current one that adds up exactly to the target.
When a group is found, it counts it as a success. To make sure the next group it finds does not share any of the same cars, it empties the notepad and starts fresh. After the notepad is cleared, it saves the current total and keeps moving forward down the track until the very end. By doing this, it makes sure every group is distinct and does not overlap with any others.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| FelixFan1122 | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| FelixFan1122 | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1319: Number of Operations to Make Network Connected
- problem 1465: Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
- problem 1477: Find Two Non-overlapping Sub-arrays Each With Target Sum
- problem 1482: Minimum Number of Days to Make m Bouquets
- problem 1488: Avoid Flood in The City
- problem 1524: Number of Sub-arrays With Odd Sum
- problem 1562: Find Latest Group of Size M
- problem 1567: Maximum Length of Subarray With Positive Product
- problem 1320: Minimum Distance to Type a Word Using Two Fingers
- problem 1697: Checking Existence of Edge Length Limited Paths
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality