Maximum Sum after Reordering

You are given an array nums of n integers, indexed from 1 to n. Additionally, there are q queries, each consisting of a pair of integers [li, ri], where 1 ≤ li ≤ ri ≤ n. For each query, your task is to find the sum of elements in the array nums from index li to index ri, inclusive.

Before processing the queries, you are allowed to reorder the elements of the array nums in any way you like to maximize the sum of all query results.

Your task is to compute the maximum possible sum of all query answers.

Example 1:

Input: nums = [5, 3, 2], queries = [[1, 2], [2, 3], [1, 3]]

Output: 25

Explanation:

By reordering the array nums = [3, 5, 2], the query sums can be maximized as:

  • Query [1, 2] => Sum = 5 + 3 = 8
  • Query [2, 3] => Sum = 5 + 2 = 7
  • Query [1, 3] => Sum = 3 + 5 + 2 = 10

Thus, the total sum is 8 + 5 + 10 = 25.

Example 2:

Input: nums = [7, 6, 9, 3], queries = [[1, 2], [2, 4], [1, 3]]

Output: 56

Explanation:

Reordering the array nums = [6, 9, 7, 3] results in:

  • Query [1, 2] => Sum = 6 + 9 = 15
  • Query [2, 4] => Sum = 9 + 7 + 3 = 19
  • Query [1, 3] => Sum = 6 + 9 + 7 = 22

Thus, the total sum is 15 + 19 + 22 = 56.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [10, 15, 5], queries = [[1, 2], [2, 3], [1, 3]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ n ≤ 2 * 105
  • 1 ≤ q ≤ 2 * 105
  • 1 ≤ nums[i] ≤ 2 * 105
  • 1 ≤ li ≤ ri ≤ n

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
long long maximumQuerySum(vector<int> &nums, vector<vector<int>> &queries) {
// Your code goes here
}
};
Test Case

Input:

Nums
Queries