{x}
blog image

Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

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] <= 104
  • 0 <= target <= 106

Solution Explanation: Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

This problem asks us to find the maximum number of non-overlapping subarrays within a given array nums whose sum equals a specified target. The solution employs a greedy approach combined with prefix sums and a hash table (or set) for efficient lookup.

Approach:

The core idea is to iteratively search for subarrays with the target sum, ensuring that we don't overlap previously found subarrays. We achieve this using the following steps:

  1. Prefix Sum: We utilize a prefix sum to efficiently calculate the sum of any subarray. The prefix sum prefix[i] represents the sum of elements from nums[0] to nums[i].

  2. Hash Table (or Set): A hash table (or set in languages like Python or Java) stores the prefix sums encountered so far. This allows for quick checks to determine if a subarray with the target sum exists.

  3. Greedy Iteration: We iterate through the array. For each index, we maintain a prefix sum and check if a subarray ending at the current index has the target sum.

    • If a subarray with the target sum is found, we increment the count of non-overlapping subarrays, reset the prefix sum, and continue the search from the next index.
    • If no such subarray is found, we continue the iteration, adding the current element to the prefix sum and updating the hash table.

Time Complexity: O(n), where n is the length of the input array nums. This is because we iterate through the array at most twice in the worst case.

Space Complexity: O(n) in the worst case, as the hash table may store up to n unique prefix sums.

Code Explanation (Python):

class Solution:
    def maxNonOverlapping(self, nums: List[int], target: int) -> int:
        ans = 0
        i, n = 0, len(nums)
        while i < n:
            s = 0  # Initialize prefix sum for the current subarray search
            vis = {0}  # Initialize a set to store prefix sums (including 0 for empty subarray)
            while i < n:
                s += nums[i]
                if s - target in vis:  #Check if a subarray with target sum exists
                    ans += 1  # Increment the count of non-overlapping subarrays
                    break  # Move to the next search starting after the found subarray
                i += 1  # Move to the next element to extend the current subarray
                vis.add(s)  # Add the current prefix sum to the set
            i += 1  # Increment i to start a new search from next index
        return ans

The other language implementations follow a similar structure, using their respective hash table or set data structures. The logic of iterative prefix sum calculation and checking for the target sum using the hash table remains consistent across all implementations.