1508. Range Sum of Sorted Subarray Sums #233
-
You are given the array Return the sum of the numbers from index Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 1508. Range Sum of Sorted Subarray Sums <?php
function rangeSum($nums, $n, $left, $right) {
$MOD = 1000000007;
$sums = array();
// Generate all subarray sums
for ($i = 0; $i < $n; $i++) {
$current_sum = 0;
for ($j = $i; $j < $n; $j++) {
$current_sum += $nums[$j];
$sums[] = $current_sum;
}
}
// Sort the sums array
sort($sums);
// Calculate the sum of the elements from left to right (1-based index)
$total = 0;
for ($i = $left - 1; $i <= $right - 1; $i++) {
$total = ($total + $sums[$i]) % $MOD;
}
return $total;
}
// Example usage
$nums = array(1, 2, 3, 4);
$n = 4;
$left = 1;
$right = 5;
echo rangeSum($nums, $n, $left, $right); // Output: 13
$left = 3;
$right = 4;
echo rangeSum($nums, $n, $left, $right); // Output: 6
$left = 1;
$right = 10;
echo rangeSum($nums, $n, $left, $right); // Output: 50
?> Explanation:
This solution efficiently generates all subarray sums, sorts them, and computes the required range sum as specified. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
left
index to theright
index (1-based).109 + 7
.Let's implement this solution in PHP: 1508. Range Sum of Sorted Subarray Sums