Range Sum of Sorted Subarray Sums - Problem
You are given an array nums consisting of n positive integers. You need to compute the sum of all non-empty continuous subarrays from the array and then sort 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 109 + 7.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,4], left = 1, right = 5
›
Output:
13
💡 Note:
All subarray sums: [1]=1, [2]=2, [3]=3, [4]=4, [1,2]=3, [2,3]=5, [3,4]=7, [1,2,3]=6, [2,3,4]=9, [1,2,3,4]=10. Sorted: [1,2,3,3,4,5,6,7,9,10]. Sum from index 1 to 5: 1+2+3+3+4 = 13
Example 2 — Small Array
$
Input:
nums = [1,2], left = 1, right = 3
›
Output:
6
💡 Note:
Subarray sums: [1]=1, [2]=2, [1,2]=3. Sorted: [1,2,3]. Sum from index 1 to 3: 1+2+3 = 6
Example 3 — Single Range
$
Input:
nums = [1,2,3,4], left = 1, right = 10
›
Output:
50
💡 Note:
All 10 subarray sums: [1,2,3,3,4,5,6,7,9,10]. Sum of all elements: 1+2+3+3+4+5+6+7+9+10 = 50
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 100
- 1 ≤ left ≤ right ≤ n * (n + 1) / 2
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original array [1,2,3,4] with range left=1, right=5
2
Generate & Sort
Create all subarray sums and sort them
3
Sum Range
Extract and sum elements from index 1 to 5
Key Takeaway
🎯 Key Insight: Generate all subarray sums, sort them, then extract the specified range sum
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code