[LeetCode] Maximum Sum Obtained of Any Permutation

1589. Maximum Sum Obtained of Any Permutation

We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + … + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.

Return the maximum total sum of all requests among all permutations of nums.

Since the answer may be too large, return it modulo 109 + 7.

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
class Solution {
public:
int maxSumRangeQuery(vector<int>& nums, vector<vector<int>>& requests) {
long long res = 0;
int mod = 1e9 + 7;
int sz = nums.size();
vector<int> freq(sz, 0);
for(auto request : requests) {
freq[request[0]]++;
if(request[1] + 1 < sz)
freq[request[1] + 1]--;
}
for(int i = 1; i < sz; i++) {
freq[i] += freq[i - 1];
}

sort(freq.begin(), freq.end());
sort(nums.begin(), nums.end());

for(int i = sz - 1; i >= 0 && freq[i]; i--) {
res = (res + 1L * freq[i] * nums[i]) % mod;
}

return res;

}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/29/PS/LeetCode/maximum-sum-obtained-of-any-permutation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.