#1546
Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
MediumArrayHash TableGreedyPrefix SumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a HashMap to keep track of prefix sums, allowing us to efficiently determine if a subarray sum equals the target. By greedily forming valid subarrays as soon as we find them, we ensure they are non-overlapping.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a HashMap to store prefix sums and a variable for the current sum.
- 2Step 2: Iterate through the array, updating the current sum and checking if (current sum - target) exists in the HashMap.
- 3Step 3: If it exists, increment the count and reset the current sum and HashMap to start a new subarray.
solution.py13 lines
1def maxNonOverlapping(nums, target):
2 count = 0
3 current_sum = 0
4 prefix_sum = {0: 1}
5 for num in nums:
6 current_sum += num
7 if (current_sum - target) in prefix_sum:
8 count += 1
9 current_sum = 0 # Reset for non-overlapping
10 prefix_sum.clear() # Clear the map
11 prefix_sum[0] = 1 # Reset prefix sum
12 prefix_sum[current_sum] = 1
13 return countℹ
Complexity note: The time complexity is O(n) because we traverse the array once, and the space complexity is O(n) due to the HashMap storing prefix sums.
- 1Using prefix sums allows us to efficiently check for subarray sums.
- 2Greedily forming subarrays as soon as we find valid ones ensures they are non-overlapping.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.