-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC - 1590. Make Sum Divisible by P
37 lines (33 loc) · 1.27 KB
/
LC - 1590. Make Sum Divisible by P
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
int minSubarray(vector<int>& nums, int p)
{
long sum = 0;
sum = accumulate(nums.begin(), nums.end(), sum);
// The valid subarrays have the sum of the form
// sumToFind, sumToFind + p, sumToFind + 2p, ...
int sumToFind = sum % p;
if(sumToFind < 0) sumToFind += p;
if(sumToFind == 0) return 0; // the whole sum is already divisible by P
// Keep track of the latest (remainder % p) of the prefix sums
unordered_map<int, int> lastRem; // <rem, lastIndex>
int prefixSum = 0;
lastRem[0] = -1;
int result = nums.size();
for(int i = 0; i < nums.size(); ++i)
{
prefixSum = (prefixSum + nums[i])%p;
if(prefixSum < 0) prefixSum += p;
// when we have prefixSum%p, we need to
// find the latest occurrence of prefix sum mod p
// equals to (prefixSum - sumToFind) % p.
int counterpart = (prefixSum - sumToFind + p)%p;
if(lastRem.count(counterpart))
{
result = min(result, i - lastRem[counterpart]);
}
lastRem[prefixSum] = i;
}
return (result == nums.size()) ? -1 : result;
}
};