Problem 1546

Abstract / Summary

Find the largest count of separate parts in an array where each part adds up to a given number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
17 lines | 388 bytes | submitted May 3, 2024 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (70k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Hash Table
  • Prefix Sum
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.93 | σ = 1.51

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
26 links | 15 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   May 3, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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