Maximum Sum Obtained of Any Permutation - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,2], requests = [[0,1],[1,3]]
Output: 11
💡 Note: Optimal permutation is [3,2,2,1]. Request [0,1] sums to 3+2=5, request [1,3] sums to 2+2+1=5. Total: 5+5=10. Wait, let me recalculate: [2,3,2,1] gives request [0,1]=2+3=5, request [1,3]=3+2+1=6, total=11.
Example 2 — Single Request
$ Input: nums = [1,2,3,4,5], requests = [[1,3]]
Output: 12
💡 Note: Place largest values at positions 1,2,3: optimal arrangement could be [1,5,4,3,2] or [2,5,4,3,1]. Request [1,3] sums to 5+4+3=12.
Example 3 — Overlapping Requests
$ Input: nums = [1,2], requests = [[0,0],[0,1]]
Output: 5
💡 Note: Optimal permutation [2,1]. Request [0,0] sums to 2, request [0,1] sums to 2+1=3. Total: 2+3=5.

Constraints

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

Visualization

Tap to expand
Maximum Sum Obtained of Any Permutation INPUT nums array: 1 [0] 2 [1] 3 [2] 2 [3] requests: Request 1: [0, 1] Sum indices 0 to 1 Request 2: [1, 3] Sum indices 1 to 3 Index Coverage: 1x 2x 1x 1x ALGORITHM STEPS 1 Count Frequency Use diff array for each index appearance count 2 Prefix Sum freq = [1, 2, 1, 1] 1 2 1 1 3 Sort Both Arrays nums: [1,2,2,3] freq: [1,1,1,2] 4 Multiply & Sum Pair largest values with highest freq 3 * 2 = 6 2 * 1 = 2 2 * 1 = 2 1 * 1 = 1 FINAL RESULT Optimal Arrangement: 2 [0] 3 [1] 2 [2] 1 [3] Request Sums: Request [0,1]: 2 + 3 = 5 indices 0 to 1 Request [1,3]: 3+2+1 = 6 indices 1 to 3 Total Sum: 11 5 + 6 = 11 [OK] Key Insight: Use a difference array to count how many times each index is queried. Sort both arrays and multiply corresponding elements (largest num with highest frequency) to maximize the total sum. TutorialsPoint - Maximum Sum Obtained of Any Permutation | Greedy with Frequency Counting
Asked in
Google 25 Amazon 20 Facebook 15
28.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen