Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
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: requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8 requests[1] -> nums[0] + nums[1] = 2 + 1 = 3 Total sum: 8 + 3 = 11. A permutation with a higher total sum is [3,5,4,2,1] with the following result: requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11 requests[1] -> nums[0] + nums[1] = 3 + 5 = 8 Total sum: 11 + 8 = 19, which is the best that you can do.
Example 2:
Input: nums = [1,2,3,4,5,6], requests = [[0,1]] Output: 11 Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].
Example 3:
Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]] Output: 47 Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].
Constraints:
n == nums.length1 <= n <= 1050 <= nums[i] <= 1051 <= requests.length <= 105requests[i].length == 20 <= starti <= endi < nProblem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[1,2,3,4,5] [[1,3],[0,1]]
[1,2,3,4,5,6] [[0,1]]
[1,2,3,4,5,10] [[0,2],[1,3],[1,1]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1589: Maximum Sum Obtained of Any Permutation
class Solution {
public int maxSumRangeQuery(int[] nums, int[][] requests) {
int n = nums.length;
int[] d = new int[n];
for (var req : requests) {
int l = req[0], r = req[1];
d[l]++;
if (r + 1 < n) {
d[r + 1]--;
}
}
for (int i = 1; i < n; ++i) {
d[i] += d[i - 1];
}
Arrays.sort(nums);
Arrays.sort(d);
final int mod = (int) 1e9 + 7;
long ans = 0;
for (int i = 0; i < n; ++i) {
ans = (ans + 1L * nums[i] * d[i]) % mod;
}
return (int) ans;
}
}
// Accepted solution for LeetCode #1589: Maximum Sum Obtained of Any Permutation
func maxSumRangeQuery(nums []int, requests [][]int) (ans int) {
n := len(nums)
d := make([]int, n)
for _, req := range requests {
l, r := req[0], req[1]
d[l]++
if r+1 < n {
d[r+1]--
}
}
for i := 1; i < n; i++ {
d[i] += d[i-1]
}
sort.Ints(nums)
sort.Ints(d)
const mod = 1e9 + 7
for i, a := range nums {
b := d[i]
ans = (ans + a*b) % mod
}
return
# Accepted solution for LeetCode #1589: Maximum Sum Obtained of Any Permutation
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
// Accepted solution for LeetCode #1589: Maximum Sum Obtained of Any Permutation
struct Solution;
const MOD: i64 = 1_000_000_007;
impl Solution {
fn max_sum_range_query(mut nums: Vec<i32>, requests: Vec<Vec<i32>>) -> i32 {
let n = nums.len();
let mut count = vec![0; n + 1];
for r in requests {
count[r[0] as usize] += 1;
count[r[1] as usize + 1] -= 1;
}
count.pop();
let mut prev = 0;
for i in 0..n {
prev += count[i];
count[i] = prev;
}
count.sort_unstable();
nums.sort_unstable();
let mut res = 0;
for i in 0..n {
res += nums[i] as i64 * count[i] as i64;
res %= MOD;
}
res as i32
}
}
#[test]
fn test() {
let nums = vec![1, 2, 3, 4, 5];
let requests = vec_vec_i32![[1, 3], [0, 1]];
let res = 19;
assert_eq!(Solution::max_sum_range_query(nums, requests), res);
let nums = vec![1, 2, 3, 4, 5, 6];
let requests = vec_vec_i32![[0, 1]];
let res = 11;
assert_eq!(Solution::max_sum_range_query(nums, requests), res);
let nums = vec![1, 2, 3, 4, 5, 10];
let requests = vec_vec_i32![[0, 2], [1, 3], [1, 1]];
let res = 47;
assert_eq!(Solution::max_sum_range_query(nums, requests), res);
}
// Accepted solution for LeetCode #1589: Maximum Sum Obtained of Any Permutation
function maxSumRangeQuery(nums: number[], requests: number[][]): number {
const n = nums.length;
const d = new Array(n).fill(0);
for (const [l, r] of requests) {
d[l]++;
if (r + 1 < n) {
d[r + 1]--;
}
}
for (let i = 1; i < n; ++i) {
d[i] += d[i - 1];
}
nums.sort((a, b) => a - b);
d.sort((a, b) => a - b);
let ans = 0;
const mod = 10 ** 9 + 7;
for (let i = 0; i < n; ++i) {
ans = (ans + nums[i] * d[i]) % mod;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.