327. Count of Range Sum
Description
Difficulty: Hard
Related Topics: Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set
Given an integer array nums
and two integers lower
and upper
, return the number of range sums that lie in [lower, upper]
inclusive.
Range sum S(i, j)
is defined as the sum of the elements in nums
between indices i
and j
inclusive, where i <= j
.
Example 1:
1 | Input: nums = [-2,5,-1], lower = -2, upper = 2 |
Example 2:
1 | Input: nums = [0], lower = 0, upper = 0 |
Constraints:
- 1 <= nums.length <= 105
- -231 <= nums[i] <= 231 - 1
- -105 <= lower <= upper <= 105
- The answer is guaranteed to fit in a 32-bit integer.
Hints/Notes
- Merge sort
Details
First we need to calculate the preSum, since the problem is about range sum. But to get the
number of range sum, the intuitive way is to check each preSum[i] against every preSum[j]
where j > i. But this solution’s time complexity is O(n^2). So we need to find a solution
with better time complexity.
The key requirement here is: for each preSum[i], we should find the preSum[j] (j > i) where
min < preSum[j] - preSum[i] < max. If for one fixed preSum[i], all preSum[j] are sorted then
it’s easy to just find the lower and upper bound of j, and count = upper - lower. This implies
that the problem can be solved with sorted fragments of the array, so merge sort would help
here. We only need to add one step during the merge.
Solution
Language: C++
1 | class Solution { |