Skip to content

Commit 324812e

Browse files
authored
Update 1590-make-sum-divisible-by-p.js
1 parent 337c11d commit 324812e

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

1590-make-sum-divisible-by-p.js

+15
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,18 @@ const minSubarray = function(nums, p) {
1818

1919
return res === nums.length ? -1 : res;
2020
};
21+
22+
/**
23+
24+
Let pre[] be the prefix sum array,
25+
then pre[i] is running prefix sum or prefix sum of i elements,
26+
pre[j] is the prefix sum such that pre[i]-pre[j] is the subarray we
27+
need to remove to make pre[n] (sum of all elements) divisible by p
28+
29+
(pre[n] - (pre[i]-pre[j])) % p = 0 ... (remove a subarray to make pre[n] divisible by p)
30+
=> pre[n] % p = (pre[i]-pre[j]) % p ... ((a-b)%m = a%m - b%m)
31+
=> pre[j]%p = pre[i]%p - pre[n]%p ... (same property used above)
32+
since RHS can be negative we make it positive modulus by adding p and taking modulus
33+
=> pre[j]%p = (pre[i]%p - pre[n]%p + p) % p
34+
35+
*/

0 commit comments

Comments
 (0)