Skip to content

1508. Range Sum of Sorted Subarray Sums #233

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

To solve this problem, we can follow these steps:

  1. Generate all possible sums of non-empty continuous subarrays.
  2. Sort the resulting array of sums.
  3. Calculate the sum of the elements from the left index to the right index (1-based).
  4. Return the result modulo 109 + 7.

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
    s…

Replies: 1 comment

Comment options

mah-shamim
Aug 4, 2024
Maintainer Author

You must be logged in to vote
0 replies
Answer selected by topugit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
1 participant