package leetcode;

/**
 * https://leetcode.com/problems/subarray-sums-divisible-by-k/
 */
public class Problem974 {
    public int subarraysDivByK(int[] A, int K) {
        int[] sums = new int[A.length];
        int sum = 0;
        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] % K == 0) {
                answer++;
            }
            for (int j = i - 1; j >= 0; j--) {
                if ((sums[i] - sums[j]) % K == 0) {
                    answer++;
                }
            }
        }
        return answer;
    }

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

@@ -173,125 +173,51 @@
  int
-%5B%5D sums = new int%5BA.length%5D;%0A        int sum = 0;%0A        for (int i = 0; i %3C A.length; i++) %7B%0A            sum += A%5Bi
+ total = 0;%0A        int%5B%5D count = new int%5BK
 %5D;%0A 
@@ -227,38 +227,22 @@
     
-    sums%5Bi
+count%5B0
 %5D 
-+
 = 
-sum
+1
 ;%0A
-        %7D%0A
     
@@ -289,20 +289,17 @@
  0; i %3C 
-sums
+A
 .length;
@@ -322,120 +322,94 @@
     
-if (sums%5Bi%5D %25 K == 0) %7B%0A                answer++;%0A            %7D%0A            for (int j = i - 1; j %3E= 0; j--) %7B%0A 
+total += A%5Bi%5D;%0A            int mod = total %25 K;%0A            // Make the mod positive.%0A
     
@@ -420,41 +420,17 @@
     
-   
 if (
-(sums%5Bi%5D - sums%5Bj%5D) %25 K ==
+mod %3C
  0) 
@@ -451,26 +451,18 @@
     
-    answer++;%0A    
+mod += K;%0A
     
@@ -487,316 +487,88 @@
     
-%7D%0A        %7D%0A        return answer;%0A    %7D%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem974 prob = new Problem974();%0A        System.out.println(prob.subarraysDivByK(new int%5B%5D%7B4, 5, 0, -2, -3, 1%7D, 5)); // 7%0A        // %5B4, 5, 0, -2, -3, 1%5D, %5B5%5D, %5B5, 0%5D, %5B5, 0, -2, -3%5D, %5B0%5D, %5B0, -2, -3%5D, %5B-2, -3%5D
+answer += count%5Bmod%5D;%0A            count%5Bmod%5D++;%0A        %7D%0A        return answer;
 %0A   

Solve problem 974