<p>Given a binary array <code>nums</code> and an integer <code>goal</code>, return <em>the number of non-empty <strong>subarrays</strong> with a sum</em> <code>goal</code>.</p>

<p>A <strong>subarray</strong> is a contiguous part of the array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,0,1,0,1], goal = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> The 4 subarrays are bolded and underlined below:
[<u><strong>1,0,1</strong></u>,0,1]
[<u><strong>1,0,1,0</strong></u>,1]
[1,<u><strong>0,1,0,1</strong></u>]
[1,0,<u><strong>1,0,1</strong></u>]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [0,0,0,0,0], goal = 0
<strong>Output:</strong> 15
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
	<li><code>0 &lt;= goal &lt;= nums.length</code></li>
</ul>

class Solution {
public:
    int numSubarraysWithSum(vector<int>& nums, int goal) {
        int n = nums.size();
        vector<int> a(n,0);
        vector<int> b(n,0);
        int zeros = 0;
        vector<int>v;
        for(int i = 0;i<n;i++){
            if(nums[i] == 1){
                a[i] = zeros;
                zeros = 0;
                v.push_back(i);
            }else{
                zeros++;
            }
        }
        zeros = 0;
        for(int i = n-1;i>=0;i--){
            if(nums[i] == 1){
                b[i] = zeros;
                zeros = 0;
            }else{
                zeros++;
            }
        }
        zeros = 0;
        if(goal == 0){
            int ans = 0;
            for(int i = 0;i<nums.size();i++){
                if(nums[i] == 0){
                    zeros++;
                }else{
                    ans+=((zeros*(zeros+1))/2);
                    zeros = 0;
                }
            }
            if(zeros != 0){
                ans+=((zeros*(zeros+1))/2);
            }
            return ans;
        }
        int i = 0,j = goal-1;
        long long  ans = 0;

        for(int i = 0;i<n;i++){
            cout<<a[i]<<" "<<b[i]<<endl;
        }
        i = 0;
        while(j<v.size()){
            ans+=((a[v[i]]+1)*(b[v[j]]+1));
            i++;
            j++;
        }

        return ans;
    }
};
34600