Show problems as
Classic problem #327HardArrayBinary SearchDivide and ConquerBinary Indexed TreeSegment TreeMerge SortOrdered SetTreap

Count of Range Sum

Real-world version: Reservoir Swing Bands
Tracked in this browser only
Read Count of Range Sum on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstPrefix Sums · Arrays, animated step by step

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.

Python
def count_range_sum(nums: list[int], lower: int, upper: int) -> int:
Java
public int countRangeSum(int[] nums, int lower, int upper)