Maximum Sum Obtained of Any Permutation — LeetCode 1589 Python Solution
MediumGreedyArrayPrefix SumSorting
- Problem
- #1589
- Pattern
- Prefix Sum
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
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
LeetCode 1838Frequency of the Most Frequent ElementMediumLeetCode 2171Removing Minimum Number of Magic BeansMediumLeetCode 2234Maximum Total Beauty of the GardensHardLeetCode 2271Maximum White Tiles Covered by a CarpetMediumLeetCode 2406Divide Intervals Into Minimum Number of GroupsMediumLeetCode 2587Rearrange Array to Maximize Prefix ScoreMedium
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.