Problem Description
Given an array of integers nums and an integer target, find the maximum number of non-empty, non-overlapping subarrays such that the sum of each subarray equals target.
Key Insights
- A greedy strategy is optimal: once you find a valid subarray, you “cut” the array and search for the next non-overlapping group.
- The use of prefix sums allows you to quickly detect if a subarray sum equals target.
- A hash set (or hash table) is used to store previously seen prefix sums within the current segment to efficiently check if (current sum - target) has appeared.
- When a valid subarray is encountered, reset the running sum and the hash set to guarantee no overlap.
Space and Time Complexity
Time Complexity: O(n) – The solution makes one pass through the array. Space Complexity: O(n) – In the worst-case scenario, the hash set could store all intermediate prefix sums (though it is reset upon finding a valid subarray).
Solution
The solution iterates through nums, computing a cumulative sum. Along the way, it stores each cumulative sum in a hash set (initially containing 0) representing the prefix sums within the current segment. At each index, check if (cumulative sum - target) exists in the set. If it does, a valid subarray ending at the current index is found; increment the count and reset both the cumulative sum and the hash set to ensure subsequent subarrays do not overlap the found subarray.
Key points:
- The hash set helps in dealing with arrays that contain negative numbers as well as positive numbers.
- Resetting when a valid subarray is found ensures that the next search starts afresh to avoid overlapping with the already counted subarray.
- This algorithm is greedy: it always takes the earliest valid subarray, which maximizes the total count.