/327. Count of Range Sum

327. Count of Range Sum

Hard
Arrays38.4% acceptance

Given an integer array arr and two integers min_sum and max_sum, return the number of contiguous subarrays (inclusive ranges) whose sum is in the interval [min_sum, max_sum]. The sum for a range [i, j] is defined as the sum of arr[i] + arr[i+1] + ... + arr[j], where 0 <= i <= j < len(arr).

Example 1

Input: arr = [3, -4, 2], min_sum = -2, max_sum = 3

Output: 4

Explanation: Valid ranges: [0,0]=3, [0,1]=-1, [1,2]=-2, [2,2]=2

Example 2

Input: arr = [1, 1, 1], min_sum = 2, max_sum = 3

Output: 4

Explanation: Valid ranges: [0,1]=2, [0,2]=3, [1,2]=2, [2,2]=1 (only 3 valid, [2,2]=1 is not in range)

Constraints

  • 1 <= len(arr) <= 105
  • -231 <= arr[i] <= 231 - 1 for all i
  • -105 <= min_sum <= max_sum <= 105
  • The result fits in a 32-bit integer
Python (current runtime)

Case 1

Input: arr = [5, -3, 1, 2], min_sum = 1, max_sum = 5

Expected: 5

Case 2

Input: arr = [-1, 2, -2, 3], min_sum = -2, max_sum = 2

Expected: 6

Case 3

Input: arr = [0, 0, 0], min_sum = 0, max_sum = 0

Expected: 6

Case 4

Input: arr = [10, -10, 10], min_sum = 0, max_sum = 10

Expected: 4