<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:
    def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
        r_zeros = [0]*len(nums)
        for i in range(len(nums)-1, -1, -1):
            if i == len(nums)-1 or nums[i+1] == 1:
                r_zeros[i] = int(nums[i] == 0)
            else:
                r_zeros[i] = int(nums[i] == 0) + r_zeros[i+1]
        print(r_zeros)
        c_sum = 0
        h = 0
        ans = 0
        for i, num in enumerate(nums):
            c_sum += num
            while c_sum>goal:
                c_sum -= nums[h]
                h += 1

            if c_sum == goal:
                if h<=i and nums[h] == 0:
                    r_h_zeros = r_zeros[h]
                    r_h_zeros = min(r_h_zeros, i-h)
                    #print(i, r_h_zeros)
                    ans += 1
                    ans += r_h_zeros
                else:
                    if h<=i:
                        ans += 1
            print(i, ans)
        return ans

18500