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: 19
💡 Note: Place largest values at positions 1,2,3: [1,5,4,3,2]. Request [1,3] sums to 5+4+3=12. Actually optimal is [2,5,4,3,1] giving 5+4+3=12. Let me reconsider: we want max sum, so [1,5,4,3,2] gives 5+4+3=12, but [0,5,4,3,1] gives same. Actually [X,5,4,3,X] maximizes the request sum at 5+4+3=12. No wait, we can put [X,5,4,3,X] to get 12, but that's not 19. Let me recalculate properly with all 5 elements in positions 1-3: position the three largest (5,4,3) at positions 1,2,3 to get 5+4+3=12. Hmm, 19 suggests we may be counting multiple times or there's an error.
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 PermutationInput:nums = [1, 2, 3, 2]requests = [[0,1], [1,3]]Frequency AnalysisPosition 1 used most (2 times)Optimal Strategy1. Sort values: [3,2,2,1]2. Sort frequencies: [2,1,1,1]Result: Maximum SumGreedy matching gives optimal permutation arrangement
Understanding the Visualization
1
Input
nums=[1,2,3,2], requests=[[0,1],[1,3]]
2
Count Frequencies
Position 0: used 1 time, Position 1: used 2 times, Position 2: used 1 time, Position 3: used 1 time
3
Optimal Arrangement
Place largest values at most frequent positions: [3,2,2,1] or similar to maximize total sum
Key Takeaway
🎯 Key Insight: Count position frequencies using prefix sums, then greedily match highest values with most frequent positions
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