Maximum Sum Obtained of Any Permutation Problem
Description
LeetCode Problem 1589.
We have an array of integers, nums, and an array of requests where requests[i] = [start_i, end_i]. The i^th request asks for the sum of nums[start_i] + nums[start_i + 1] + ... + nums[end_i - 1] + nums[end_i]. Both start_i and end_i 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 10^9 + 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.length1 <= n <= 10^50 <= nums[i] <= 10^51 <= requests.length <= 10^5requests[i].length == 20 <= start_i <= end_i < n
Solution
Approach: Difference Array + Sorting + Greedy
The total of all requests is the sum over positions of nums[i] * cover[i], where cover[i] is how many requests include index i. We are free to permute nums, so we just decide which value goes to which position. The best choice is to give the largest value to the most covered position, the second largest to the second most covered, and so on (swapping any pair that is out of this order can only increase the sum).
To compute cover without walking every range, use a difference array: for each request [l, r] add 1 at l and subtract 1 at r + 1. A prefix sum then gives the coverage of every index.
Sort cover and nums, multiply them position by position, and add the products modulo 10^9 + 7. A single product can reach 10^5 * 10^5, so use 64-bit integers.
Complexity: O(n log n + q) time, where q is the number of requests, and O(n) extra space.
class Solution:
def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:
n = len(nums)
# difference array: after the prefix sum, cnt[i] = number of requests covering index i
cnt = [0] * (n + 1)
for l, r in requests:
cnt[l] += 1
cnt[r + 1] -= 1
for i in range(1, n):
cnt[i] += cnt[i - 1]
cnt = sorted(cnt[:n])
nums = sorted(nums)
# the most covered index gets the largest number, and so on
return sum(a * b for a, b in zip(nums, cnt)) % (10**9 + 7)