[LeetCode] Binary Subarrays With Sum

930. Binary Subarrays With Sum

Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.

A subarray is a contiguous part of the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int numSubarraysWithSum(vector<int>& nums, int goal) {
unordered_map<int, int> mp{{0,1}};
int res = 0;
for(int i = 0, sum = 0; i < nums.size(); i++) {
sum += nums[i];
res += mp[sum-goal];
mp[sum]++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/19/PS/LeetCode/binary-subarrays-with-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.