Range Sum of Sorted Subarray Sums Problem
Description
LeetCode Problem 1508.
You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.
Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 10^9 + 7.
Example 1:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 5
Output: 13
Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
Example 2:
Input: nums = [1,2,3,4], n = 4, left = 3, right = 4
Output: 6
Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
Example 3:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 10
Output: 50
Constraints:
n == nums.length1 <= nums.length <= 10001 <= nums[i] <= 1001 <= left <= right <= n * (n + 1) / 2
Solution
Approach: List All Subarray Sums and Sort
With n <= 1000 there are at most n * (n + 1) / 2 = 500500 subarrays, few enough to list them all.
For each start index i, extend the subarray one element at a time to the right, keeping a running sum, and record every sum. This produces all subarray sums in O(n2) without recomputing anything. Sort them, add up the entries at positions left through right (1-indexed, so indices left - 1 to right - 1), and return the total modulo 10^9 + 7.
Each sum is at most 1000 * 100 = 10^5, so it fits in an int, but the total of up to 500500 of them can reach about 5 * 10^10. Accumulate in a 64-bit integer (long in Java, long long in C++) before taking the remainder.
Complexity: O(n2 log n) time for sorting the n2/2 sums, and O(n2) space.
class Solution:
def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
sums = []
for i in range(n):
s = 0
for j in range(i, n):
s += nums[j]
sums.append(s) # sum of nums[i..j]
sums.sort()
return sum(sums[left - 1 : right]) % (10**9 + 7)