Maximum Number of Non-Overlapping Subarrays With Sum Equals Target — LeetCode 1546 Python Solution

MediumGreedyArrayHash TablePrefix Sum
Problem
#1546
Pattern
Prefix Sum
Reading time
3 min

The problem

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

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).

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target?
LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target is rated Medium on LeetCode.
What is the time complexity of LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target cover?
LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target is tagged Greedy, Array, Hash Table and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview