diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /binary_subarr_sum.py | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'binary_subarr_sum.py')
-rw-r--r-- | binary_subarr_sum.py | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/binary_subarr_sum.py b/binary_subarr_sum.py new file mode 100644 index 0000000..75a9df7 --- /dev/null +++ b/binary_subarr_sum.py @@ -0,0 +1,30 @@ +# 930. Binary Subarrays With Sum +import collections + +""" +given a binary array 'nums' and an integer 'goal', return the number o +non-empty subarrays with a sum 'goal'. a subarray is a contiguous part of the +array + """ + + +class Solution(object): + def numSubarraysWithSum(self, nums, goal): + """ + :type nums: List[int] + :type goal: int + :rtype: int + """ + c = collections.Counter({0: 1}) + psum = ans = 0 + for i in nums: + psum += i + ans += c[psum - goal] + c[psum] += 1 + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.numSubarraysWithSum(nums=[1, 0, 1, 0, 1], goal=2)) + print(obj.numSubarraysWithSum(nums=[0, 0, 0, 0, 0], goal=0)) |