Skip to content

Commit 091ae0b

Browse files
authored
Create maximum-sum-obtained-of-any-permutation.cpp
1 parent 538979b commit 091ae0b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int maxSumRangeQuery(vector<int>& nums, vector<vector<int>>& requests) {
7+
static const int MOD = 1e9 + 7;
8+
9+
vector<int> count(size(nums));
10+
for (const auto& req : requests) {
11+
++count[req[0]];
12+
if (req[1] + 1 < size(count)) {
13+
--count[req[1] + 1];
14+
}
15+
}
16+
partial_sum(begin(count), end(count), begin(count));
17+
sort(begin(nums), end(nums));
18+
sort(begin(count), end(count));
19+
int result = 0;
20+
for (int i = 0; i < size(nums); ++i) {
21+
result = addmod(result, mulmod(nums[i], count[i], MOD), MOD);
22+
}
23+
return result;
24+
}
25+
26+
private:
27+
uint32_t addmod(uint32_t a, uint32_t b, uint32_t mod) { // avoid overflow
28+
a %= mod, b %= mod;
29+
if (mod - a <= b) {
30+
b -= mod; // relied on unsigned integer overflow in order to give the expected results
31+
}
32+
return a + b;
33+
}
34+
35+
// reference: https://stackoverflow.com/questions/12168348/ways-to-do-modulo-multiplication-with-primitive-types
36+
uint32_t mulmod(uint32_t a, uint32_t b, uint32_t mod) { // avoid overflow
37+
a %= mod, b %= mod;
38+
uint32_t result = 0;
39+
if (a < b) {
40+
swap(a, b);
41+
}
42+
while (b > 0) {
43+
if (b % 2 == 1) {
44+
result = addmod(result, a, mod);
45+
}
46+
a = addmod(a, a, mod);
47+
b /= 2;
48+
}
49+
return result;
50+
}
51+
};

0 commit comments

Comments
 (0)