Subarray Sums Divisible by K
Description
Given an array A
of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K
.
Example 1:
Input: A = [4,5,0,-2,-3,1], K = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by K = 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Note:
1 <= A.length <= 30000
-10000 <= A[i] <= 10000
2 <= K <= 10000
Solution(javascript)
/** 可以用 Prefix Sum 来解吗
* https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/310767/(Python)-Concise-Explanation-and-Proof
* @param {number[]} A
* @param {number} K
* @return {number}
*/
const subarraysDivByK = function (A, K) {
let sum = 0
const map = { 0: 1 }
let count = 0
for (const num of A) {
sum += num
// 注意负数的情况
const key = ((sum % K) + K) % K
if (map[key]) {
count += map[key]
map[key] += 1
} else {
map[key] = 1
}
}
return count
}