-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0974.SubarraySumsDivisibleByK.cpp
More file actions
44 lines (37 loc) · 970 Bytes
/
0974.SubarraySumsDivisibleByK.cpp
File metadata and controls
44 lines (37 loc) · 970 Bytes
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
38
39
40
41
42
43
44
class Solution {
public:
int subarraysDivByK(vector<int>& nums, int k) {
// Speed thingies.
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// Calculation variables.
unordered_map<int, int> activeRemainders;
activeRemainders.emplace(0, 1);
int totalSum = 0;
// Find valid count.
int validSubarrays = 0;
const int n = nums.size();
for (int i = 0; i < n; i++) {
// Update sum.
totalSum += nums[i];
// Get remainder.
int remainder = totalSum % k;
while (remainder < 0) remainder += k;
// Check if remainder exists.
const auto it = activeRemainders.find(remainder);
if (it == activeRemainders.end()) {
// Add index to collection.
activeRemainders.emplace(remainder, 1);
continue;
}
// Valid subarray combination found.
// Update count.
validSubarrays += it->second;
// Update tracked count.
it->second++;
}
// No valid case found.
return validSubarrays;
}
};