930. Binary Subarrays With Sum
In an array A of 0s and 1s, 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 <= 300000 <= S <= A.lengthA[i]is either0or1.
# @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=endnum_subarrays_with_sum (generic function with 1 method)
This page was generated using DemoCards.jl and Literate.jl.