LeetCode 1508: Range Sum of Sorted Subarray Sums

Problem Description

Explanation

To solve this problem, we can iterate over all possible subarrays of the given array nums, calculate the sum of each subarray, sort these sums in non-decreasing order, and then find the sum of the numbers between the given indices left and right in the sorted array.

Here is the step-by-step algorithm:

  1. Initialize an ArrayList to store all subarray sums.
  2. Iterate over all subarrays of nums and calculate the sum of each subarray.
  3. Add each subarray sum to the ArrayList.
  4. Sort the ArrayList in non-decreasing order.
  5. Calculate the sum of the numbers between the indices left and right in the sorted ArrayList.
  6. Return the sum modulo 10^9 + 7.

Time complexity: O(n^2 * log(n^2)) where n is the length of the input array nums. Space complexity: O(n^2) to store all subarray sums.

Solutions

import java.util.ArrayList;
import java.util.Collections;

class Solution {
    public int rangeSum(int[] nums, int n, int left, int right) {
        ArrayList<Integer> sums = new ArrayList<>();
        
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = i; j < n; j++) {
                sum += nums[j];
                sums.add(sum);
            }
        }
        
        Collections.sort(sums);
        
        int result = 0;
        for (int i = left - 1; i <= right - 1; i++) {
            result = (result + sums.get(i)) % 1000000007;
        }
        
        return result;
    }
}

Loading editor...