930. Binary Subarrays With Sum
In an array A
of 0
s and 1
s, how many non-empty subarrays have sum S
?
Example 1:
Input: A = [1,0,1,0,1], S = 2
Output: 4
Explanation:
The 4 subarrays are bolded below:
[ **1,0,1** ,0,1]
[ **1,0,1,0** ,1]
[1, **0,1,0,1** ]
[1,0, **1,0,1** ]
Note:
A.length <= 30000
0 <= S <= A.length
A[i]
is either0
or1
.
# @lc code=start
using LeetCode
function num_subarrays_with_sum(nums::Vector{Int}, goal::Int)
cnt = OffsetArray(fill(0, length(nums) + 1), -1)
s, res = 0, 0
for num in nums
cnt[s] += 1
s += num
res += get(cnt, s - goal, 0)
end
res
end
# @lc code=end
num_subarrays_with_sum (generic function with 1 method)
This page was generated using DemoCards.jl and Literate.jl.