ZolostaysOA #1
Range Sum
Estimated HardJudge-ready
Topics (AI-labelled)Prefix & RangesBinary Search
Given an integer array arr and a closed interval [lower, upper], count how many contiguous non-empty subarrays have an element sum within the interval. Equal subarrays are counted separately by start and end positions. The fixed source's second example output is corrected from 8 to 13; the basis is in the notes.
Input
The first line contains n (1≤n≤50000); the second line contains n 32-bit signed integers; the third line contains lower upper (both 32-bit signed integers with lower≤upper).
Output
Output the number of contiguous subarrays whose sum lies in the closed interval [lower, upper].
Example 1
Input:
3
-2 5 -1
-2 2
Output:
3
Example 2
Input:
7
1 -3 5 2 5 2 -5
-2 6
Output:
13
Example 3
Input:
8
1 -3 5 -2 2 5 -1 10
5 9
Output:
12
Example notes
Use prefix sums to turn a range sum into the difference of two prefix sums, then count in O(n log n) time with merge sort and two pointers. The source output of the second public example was mistakenly written as 8; enumerating directly by definition gives 13.
Editorial
Loading solution…