Jun 22, 2024
[1,0,1,1,0] and goal 2, the valid subarrays are [1,1,0], [1,1], [1,1], and [1,0,1] (total: 4).O(n) time and O(n) space complexities.O(n) time and O(1) space complexity.[1,0,1,1,0], goal 2.L and R at 0, and sum and count at 0.sum while moving R.sum exceeds goal, move L to shrink the window until sum <= goal.sum = 0, count = 00: sum = 1 (Valid subarray count = 1)1: sum = 1 (Valid subarray count = 2)2: sum = 2 (Valid subarray count = 3)R to 3, shrink window by moving L to 1: sum = 2R to 4, L to 2: sum = 2O(n) time, O(1) space.goal.def count_subarrays_with_sum(nums, goal):
def count_sub_arrays_with_sum_lte(nums, goal):
L = 0
current_sum = 0
count = 0
for R in range(len(nums)):
current_sum += nums[R]
while current_sum > goal:
current_sum -= nums[L]
L += 1
count += R - L + 1
return count
if goal < 0:
return 0
return count_sub_arrays_with_sum_lte(nums, goal) - count_sub_arrays_with_sum_lte(nums, goal - 1)
O(1).O(n) time and O(1) space complexity.