Formatted question description: https://leetcode.ca/all/1589.html

1589. Maximum Sum Obtained of Any Permutation (Medium)

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.

Example 1:

Input: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]
Output: 19
Explanation: One permutation of nums is [2,1,3,4,5] with the following result:
requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8
requests[1] -> nums[0] + nums[1] = 2 + 1 = 3
Total sum: 8 + 3 = 11.
A permutation with a higher total sum is [3,5,4,2,1] with the following result:
requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11
requests[1] -> nums[0] + nums[1] = 3 + 5  = 8
Total sum: 11 + 8 = 19, which is the best that you can do.


Example 2:

Input: nums = [1,2,3,4,5,6], requests = [[0,1]]
Output: 11
Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].

Example 3:

Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]
Output: 47
Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].

Constraints:

• n == nums.length
• 1 <= n <= 105
• 0 <= nums[i] <= 105
• 1 <= requests.length <= 105
• requests[i].length == 2
• 0 <= starti <= endi < n

Related Topics:
Greedy

Solution 1.

For each requests[i], add 1 at cnt[requests[i][0]] and subtract 1 at cnt[requests[i][1] + 1]. Then compute prefix sum in-place on cnt, cnt[i] becomes the corresponding count of nums[i].

Sort cnt and nums, and the sum of nums[i] * cnt[i] is the answer.

// OJ: https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/

// Time: O(NlogN)
// Space: O(N)
class Solution {
public:
int maxSumRangeQuery(vector<int>& A, vector<vector<int>>& R) {
long mod = 1e9+7, N = A.size(), ans = 0;
vector<int> cnt(N);
for (int i = 0; i < R.size(); ++i) {
if (R[i][1] < N - 1) cnt[R[i][1] + 1]--;
cnt[R[i][0]]++;
}
for (int i = 1; i < N; ++i) cnt[i] += cnt[i - 1];
sort(begin(cnt), end(cnt));
sort(begin(A), end(A));
for (int i = 0; i < N; ++i) ans = (ans + (A[i] * cnt[i]) % mod) % mod;
return ans;
}
};


Java

class Solution {
public int maxSumRangeQuery(int[] nums, int[][] requests) {
final int MODULO = 1000000007;
int length = nums.length;
int[] counts = new int[length];
for (int[] request : requests) {
int start = request[0], end = request[1];
counts[start]++;
if (end + 1 < length)
counts[end + 1]--;
}
for (int i = 1; i < length; i++)
counts[i] += counts[i - 1];
Arrays.sort(counts);
Arrays.sort(nums);
long sum = 0;
for (int i = 0; i < length; i++)
sum += (long) nums[i] * counts[i];
return (int) (sum % MODULO);
}
}