package leetcode;

/**
 * https://leetcode.com/problems/binary-subarrays-with-sum/
 */
public class Problem930 {
    public int numSubarraysWithSum(int[] A, int S) {
        int sum = 0;
        int[] sums = new int[A.length];
        for (int i = 0; i < A.length; i++) {
            sum += A[i];
            sums[i] += sum;
        }
        int answer = 0;
        for (int i = 0; i < sums.length; i++) {
            if (sums[i] == S) {
                answer++;
            }
            if (sums[i] >= S) {
                int j = 0;
                while (j < i) {
                    int diff = sums[i] - sums[j];
                    if (diff == S) {
                        answer++;
                    } else if (diff < S) {
                        break;
                    }
                    j++;
                }
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Problem930 prob = new Problem930();
        System.out.println(prob.numSubarraysWithSum(new int[]{1, 0, 1, 0, 1}, 2)); // 4
        System.out.println(prob.numSubarraysWithSum(new int[]{0, 1, 1, 1, 1}, 3)); // 3
    }
}

@@ -424,18 +424,17 @@
 sums%5Bi%5D 
-==
+%3C
  S) %7B%0A  
@@ -443,32 +443,32 @@
             
-answer++
+continue
 ;%0A          
@@ -499,9 +499,9 @@
 %5Bi%5D 
-%3E
+=
 = S)
@@ -499,32 +499,68 @@
 %5Bi%5D == S) %7B%0A    
+            answer++;%0A            %7D%0A
             int 
@@ -562,28 +562,24 @@
  int j = 0;%0A
-    
             
@@ -606,28 +606,24 @@
             
-  
-  
 int diff = s
@@ -640,20 +640,16 @@
 ums%5Bj%5D;%0A
-    
         
@@ -665,18 +665,17 @@
 f (diff 
-==
+%3C
  S) %7B%0A  
@@ -688,38 +688,35 @@
             
-    answer++;%0A
+break;%0A    
             
@@ -715,24 +715,26 @@
         
+%7D%0A
         
 %7D else i
@@ -729,14 +729,15 @@
     
-%7D else
+       
  if 
@@ -734,33 +734,34 @@
        if (diff 
-%3C
+==
  S) %7B%0A          
@@ -766,33 +766,32 @@
             
-    break
+answer++
 ;%0A          
@@ -792,34 +792,26 @@
             
- 
-   %7D%0A    
+%7D%0A
             
@@ -819,34 +819,16 @@
    j++;%0A
-                %7D%0A
         
@@ -875,279 +875,7 @@
    %7D
-%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem930 prob = new Problem930();%0A        System.out.println(prob.numSubarraysWithSum(new int%5B%5D%7B1, 0, 1, 0, 1%7D, 2)); // 4%0A        System.out.println(prob.numSubarraysWithSum(new int%5B%5D%7B0, 1, 1, 1, 1%7D, 3)); // 3%0A    %7D
 %0A%7D%0A

Solve problem 930