File tree 1 file changed +19
-19
lines changed
scripts/algorithms/S/Sum of Floored Pairs
1 file changed +19
-19
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 687 ms (Top 46.29%) | Memory: 121.4 MB (Top 57.71%)
1
2
class Solution {
2
-
3
+
3
4
private:
4
-
5
+
5
6
int MOD = 1e9 + 7 ;
6
-
7
+
7
8
public:
8
-
9
+
9
10
int sumOfFlooredPairs (vector<int >& nums) {
10
11
11
12
// first of all, we record the max value
12
13
int max_n = INT_MIN;
13
14
for (int n : nums) max_n = max (max_n, n);
14
-
15
+
15
16
// then the occurences for each number in [0, max]
16
17
vector<int > occs (max_n + 1 , 0 );
17
18
for (int n : nums) occs[n]++;
18
-
19
+
19
20
// prefix sum algorithm to accumulate the occurences
20
21
vector<int > occs_acc (max_n + 1 , 0 );
21
22
for (int i = 1 ; i < max_n + 1 ; ++i) {
22
- occs_acc[i] = occs[i] + occs_acc[i - 1 ];
23
+ occs_acc[i] = occs[i] + occs_acc[i - 1 ];
23
24
}
24
-
25
+
25
26
// long long needed to prevent overflows
26
- long long ans = 0 ;
27
+ long long ans = 0 ;
27
28
for (int i = 0 ; i < max_n + 1 ; ++i) {
28
-
29
+
29
30
// just handle numbers that occur at least once
30
31
if (occs[i] != 0 ) {
31
-
32
+
32
33
int k = 1 ;
33
34
int k_next;
34
-
35
+
35
36
// for each multiple of i
36
37
do {
37
-
38
+
38
39
k_next = k + 1 ;
39
40
40
- // "right and left" multipliers in occs_acc
41
+ // "right and left" multipliers in occs_acc
41
42
int r = min (k_next * i - 1 , max_n);
42
43
int l = k * i - 1 ;
43
-
44
+
44
45
ans += ((long long ) occs_acc[r] - (long long ) occs_acc[l]) * (long long ) occs[i] * k++;
45
-
46
-
46
+
47
47
} while (k_next * i - 1 < max_n);
48
48
}
49
49
}
50
-
50
+
51
51
return ans % MOD;
52
52
}
53
- };
53
+ };
You can’t perform that action at this time.
0 commit comments