Problem 1589

Abstract / Summary

Given an array, find the maximum possible sum by multiplying each element by its position index after rearranging the elements.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1589.py

class Solution:
    def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:
        size = len(nums)

        # track begin and end of each interval
        delta = [ 0 ] * size
        for left, right in requests:
            delta[left] += 1
            if right + 1 < size:
                delta[right + 1] -= 1

        # how often is each position part of any interval
        usage = []
        have  = 0
        for d in delta:
            have += d
            usage.append(have)

        # place high numbers at positions which are used often
        usage.sort()
        nums .sort()
        return sum([ u * n for u, n in zip(usage, nums) ]) % 1_000_000_007
22 lines | 714 bytes | submitted March 1, 2024 | GitHub   18% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 41% (70k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Prefix Sum
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of maximizing the sum of values taken from an array nums according to a set of range queries requests. Each request specifies a closed interval [left, right] and contributes the value at every position inside the interval to the total sum. The algorithm determines how many times each index of nums participates in any request, then pairs the most frequently used positions with the largest numbers to achieve the maximal possible sum. The final result is returned modulo 1 000 000 007.

Key Steps

1. Build a difference array to capture interval boundaries

The algorithm first creates an auxiliary array delta of the same length as nums. For each request [left, right] it increments delta[left] and, when the interval does not end at the last index, decrements delta[right + 1]. This pattern records the start and end of every interval in a compact form.

size = len(nums)
delta = [0] * size
for left, right in requests:
    delta[left] += 1
    if right + 1 < size:
        delta[right + 1] -= 1

2. Convert the difference array into a usage count per position

A running total have is accumulated while iterating over delta. After each addition, the current total represents how many intervals cover the current index. These totals are collected into the list usage.

usage = []
have = 0
for d in delta:
    have += d
    usage.append(have)

3. Sort the usage frequencies and the original numbers

Both usage and nums are sorted in non-decreasing order. Aligning the two sorted sequences ensures that the largest numbers are placed at the positions with the highest usage counts, which yields the maximal sum.

usage.sort()
nums.sort()

4. Compute the weighted sum and apply the modulus

The final sum is obtained by multiplying each sorted number with its corresponding usage frequency and accumulating the products. The result is reduced modulo 1 000 000 007 before being returned.

return sum([u * n for u, n in zip(usage, nums)]) % 1_000_000_007

Edge Cases Handled

When the list of requests is empty, the loop that updates delta never executes, leaving delta filled with zeros. Consequently, the usage list becomes a sequence of zeros, and the weighted sum evaluates to zero, which is the correct answer.

If a request spans the entire array, the increment at delta[0] is balanced by a decrement that is omitted because right + 1 equals size. The running total have therefore remains positive for every index, correctly reflecting that each position participates in the request.

Requests that start at the first index (left == 0) or end at the last index (right == size - 1) are processed without index-out-of-range errors because the code checks the bound before applying the decrement.

The modulo operation at the end guarantees that even when the intermediate sum exceeds the range of standard integer types, the final returned value stays within the required limits.

Performance Optimizations

The use of a difference array (delta) avoids the need to iterate over every element of every request. Instead, each request contributes only two constant-time updates, and a single linear pass converts these differences into the full usage counts. This reduces the overall work to linear time with respect to the length of nums.

Sorting both usage and nums leverages highly optimized library implementations of quicksort/mergesort hybrids, which are tuned for typical data distributions and cache behavior. By sorting in place, the algorithm minimizes additional memory allocations.

The final accumulation uses a list comprehension inside sum, which is executed in C-level loops inside the Python interpreter, offering faster execution than an explicit Python for loop.

Overall, the combination of a linear-time prefix-sum construction, efficient sorting, and a tight aggregation step yields a solution that scales well for large inputs while staying within the constraints of the problem.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of empty toy boxes and a handful of special labels that say where to put your favorite toys. Some toys get asked for more often than others, so you want to make sure the biggest, shiniest toys are in the boxes that are chosen the most.

First, look at the row of boxes and make a little map to see which boxes are asked for the most. You start at the beginning of the row and walk to the end. Every time a request starts, you add a mark to that box, and every time a request finishes, you take a mark away. By walking once across the row and keeping track of these marks, you figure out exactly how many times each specific box is needed.

Once you know which boxes are the superstars because they are used the most, you grab your pile of toys and sort them so the biggest one is at the top. You also sort the box popularity list from smallest to largest. Now you just slide the biggest toy into the box that gets used the most, the second biggest toy into the box that gets used the next most, and keep going until every spot is filled. By putting the best toys in the best spots, you end up with the biggest total score possible.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.52 | σ = 1.64

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
wisdompeak C++
24 links | 13 authors | 7 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 medium 3 hard
5 solutions   March 1, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality