forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsum-of-special-evenly-spaced-elements-in-array.cpp
32 lines (30 loc) · 1.19 KB
/
sum-of-special-evenly-spaced-elements-in-array.cpp
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
// Time: O(n * sqrt(n))
// Space: O(n * sqrt(n))
class Solution {
public:
vector<int> solve(vector<int>& nums, vector<vector<int>>& queries) {
static const int MOD = 1e9 + 7;
vector<vector<vector<int>>> prefix(floor(sqrt(size(queries))) + 1, vector<vector<int>>(floor(sqrt(size(queries))) + 1));
vector<int> result;
for (const auto& query : queries) {
int x = query[0], y = query[1];
if (uint64_t(y) * y > size(queries)) {
int total = 0;
for (int i = x; i < size(nums); i += y) {
total = (total + nums[i]) % MOD;
}
result.emplace_back(total);
} else {
int begin = x % y;
if (empty(prefix[begin][y])) {
prefix[begin][y].emplace_back(0);
for (int i = begin; i < size(nums); i += y) {
prefix[begin][y].emplace_back((prefix[begin][y].back() + nums[i]) % MOD);
}
}
result.emplace_back((prefix[begin][y].back() - prefix[begin][y][x / y] + MOD) % MOD);
}
}
return result;
}
};