Count of Range Sum
Real-world version: Reservoir Swing BandsThe statement here is our own: the same inputs, outputs and technique.
A reservoir logs one net level change per hour in nums, where a negative entry means the level dropped that hour and a positive entry means it rose.
A stretch is any run of one or more consecutive hours, written nums[i .. j] with i <= j. Its swing is the sum of the entries it covers. Two stretches are different when their hour ranges differ, even if their swings agree.
Given the inclusive band lower to upper, return how many stretches have a swing of at least lower and at most upper.
Examples
Example 1
- Input
- nums = [3,-4,2,5,-6], lower = -1, upper = 4
- Output
- 8
Eight stretches land inside the band: `nums[0..0]`, `nums[0..1]`, `nums[0..2]`, `nums[0..4]`, `nums[1..3]`, `nums[2..2]`, `nums[2..4]` and `nums[3..4]`, with swings of 3, -1, 1, 0, 3, 2, 1 and -1. Every one of those swings sits between -1 and 4 inclusive.
Example 2
- Input
- nums = [8,-8], lower = 0, upper = 0
- Output
- 1
Only `nums[0..1]` sums to 0. The single-hour stretches swing by 8 and -8, both outside the band.
Example 3
- Input
- nums = [6], lower = 6, upper = 9
- Output
- 1
The one stretch available swings by 6, and 6 lies inside the band because both ends of the band count.
Constraints
- 1 <= nums.length <= 10^5
- -2^31 <= nums[i] <= 2^31 - 1
- -10^5 <= lower <= upper <= 10^5
- The count always fits in a signed 32-bit integer.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def count_range_sum(nums: list[int], lower: int, upper: int) -> int:public int countRangeSum(int[] nums, int lower, int upper)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's