MediumNo. 1589
Maximum Sum Obtained of Any Permutation — LeetCode 1589 Python Solution
- Pattern
- Prefix Sum
- Topics
- Greedy, Array, Prefix Sum, Sorting
- Reading time
- 3 min
- Source
- leetcode.com
The 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] + ...
Example
- 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:
Python solution
class Solution:
def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:
n = len(nums)
d = [0] * n
for l, r in requests:
d[l] += 1
if r + 1 < n:
d[r + 1] -= 1
for i in range(1, n):
d[i] += d[i - 1]
nums.sort()
d.sort()
mod = 10**9 + 7
return sum(a * b for a, b in zip(nums, d)) % modComplexity
- Time
- O(n log n)
- Space · auxiliary
- O(1) to O(n)
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 1589. Maximum Sum Obtained of Any Permutation is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1838 | Frequency of the Most Frequent Element | Medium |
| 2171 | Removing Minimum Number of Magic Beans | Medium |
| 2234 | Maximum Total Beauty of the Gardens | Hard |
| 2271 | Maximum White Tiles Covered by a Carpet | Medium |
| 2406 | Divide Intervals Into Minimum Number of Groups | Medium |
| 2587 | Rearrange Array to Maximize Prefix Score | Medium |
Frequently asked questions
- How hard is LeetCode 1589. Maximum Sum Obtained of Any Permutation?
LeetCode 1589. Maximum Sum Obtained of Any Permutation is rated Medium on LeetCode.
- What topics does LeetCode 1589. Maximum Sum Obtained of Any Permutation cover?
LeetCode 1589. Maximum Sum Obtained of Any Permutation is tagged Greedy, Array, Prefix Sum and Sorting on LeetCode.