To solve this problem, we need to find the maximum number of non-overlapping subarrays where each subarray sums to a given target value. The key insight here is to use a greedy approach, where we take the earliest possible subarray that sums to the target and then move past it to look for the next valid subarray. This ensures we maximize the count of non-overlapping subarrays.
Approach
- Sliding Window Technique: We use two pointers (
leftandright) to maintain a sliding window over the array. - Current Sum Tracking: We keep track of the sum of elements within the current window.
- Adjust Window: If the current sum exceeds the target, we move the left pointer to the right to reduce the sum until it is less than or equal to the target.
- Count Valid Subarrays: When the current sum equals the target, we increment the count of valid subarrays, reset the current sum, and move the left pointer to the position right after the current right pointer to avoid overlapping.
Solution Code
def max_non_overlapping_subarrays(nums, target):
left = 0
current_sum = 0
count = 0
n = len(nums)
for right in range(n):
current_sum += nums[right]
# Reduce the window from the left if sum exceeds target
while current_sum > target:
current_sum -= nums[left]
left += 1
# If sum equals target, increment count and reset for next subarray
if current_sum == target:
count += 1
current_sum = 0
left = right + 1
return count
Explanation
- Initialization: We start with
leftpointer at 0,current_sumat 0, andcountat 0. - Iterate with Right Pointer: For each element (using
rightpointer), we add it tocurrent_sum. - Adjust Left Pointer: If
current_sumexceeds the target, we move theleftpointer to the right, subtracting the element atleftfromcurrent_sumuntilcurrent_sumis <= target. - Check for Target Sum: When
current_sumequals the target, we increment the count, resetcurrent_sumto 0, and setlefttoright + 1to start looking for the next non-overlapping subarray.
This approach efficiently finds the maximum number of non-overlapping subarrays with a time complexity of O(n) (since each element is processed at most twice: once by the right pointer and once by the left pointer). The space complexity is O(1) as we only use a few variables for tracking.
Examples:
- For
nums = [1,1,1,1,1]andtarget = 2, the output is 2. - For
nums = [2,2,2,2,2]andtarget =4, the output is 2. - For
nums = [1,1,2,1,1]andtarget=2, the output is3.
This solution handles all edge cases and ensures optimal performance.


作者声明:本文包含人工智能生成内容。