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:
- Initialize an ArrayList to store all subarray sums.
- Iterate over all subarrays of
nums
and calculate the sum of each subarray. - Add each subarray sum to the ArrayList.
- Sort the ArrayList in non-decreasing order.
- Calculate the sum of the numbers between the indices
left
andright
in the sorted ArrayList. - 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...