Maximum Sum Obtained of Any Permutation — LeetCode 1589 Python Solution

MediumGreedyArrayPrefix SumSorting
Problem
#1589
Pattern
Prefix Sum
Reading time
3 min

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)) % mod

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview