From 8ca71e1234f46e9ee60b60a482e859b8ce56319c Mon Sep 17 00:00:00 2001 From: Shahriar Shatil <52494840+ShatilKhan@users.noreply.github.com> Date: Thu, 14 Mar 2024 23:16:52 +0600 Subject: [PATCH] Time: 237 ms (12.61%) | Memory: 17.1 MB (99.51%) - LeetSync --- .../binary-subarrays-with-sum.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 966-binary-subarrays-with-sum/binary-subarrays-with-sum.py diff --git a/966-binary-subarrays-with-sum/binary-subarrays-with-sum.py b/966-binary-subarrays-with-sum/binary-subarrays-with-sum.py new file mode 100644 index 0000000..285efc2 --- /dev/null +++ b/966-binary-subarrays-with-sum/binary-subarrays-with-sum.py @@ -0,0 +1,16 @@ +class Solution: + def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: + def helper(x): + if x < 0: return 0 + + res = 0 + l, cur = 0, 0 + for r in range(len(nums)): + cur += nums[r] + while cur > x: + cur -= nums[l] + l += 1 + res += (r - l + 1) + return res + + return helper(goal) - helper(goal - 1) \ No newline at end of file