All problems
0344HardArrayBinary SearchDivide and ConquerBinary Indexed TreeSegment TreeMerge SortOrdered SetTreap

Reservoir Swing Bands

Tracked in this browser only
Write code

Trains the technique from

LeetCode 327Count of Range Sum

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a 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)
September 7
Apply