Home > Article > Backend Development > Range Sum of Sorted Subarray Sums
1508. Range Sum of Sorted Subarray Sums
Medium
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 109 + 7.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 1508. Range Sum of Sorted Subarray Sums
Explanation:
Generating Subarray Sums:
- Iterate through each starting index i of the subarray.
- For each starting index i, compute the sum of subarrays ending at index j (where j >= i).
- Append each computed subarray sum to the $sums array.
Sorting the Sums:
- Use PHP's sort() function to sort the $sums array in non-decreasing order.
Summing the Required Range:
- Iterate from the left-1 index to the right-1 index (since the problem uses 1-based indexing).
- Accumulate the sum of the elements in this range, taking care to use modulo 109 + 7 to avoid overflow.
This solution efficiently generates all subarray sums, sorts them, and computes the required range sum as specified.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Range Sum of Sorted Subarray Sums. For more information, please follow other related articles on the PHP Chinese website!