Блог пользователя code_fille

Автор code_fille, история, 11 лет назад, По-английски

Given an array of integers and a range find the count of subarrays whose sum lies in the given range. Do so in less than O(n^2) complexity.

  • Проголосовать: нравится
  • +5
  • Проголосовать: не нравится

»
11 лет назад, скрыть # |
Rev. 6  
Проголосовать: нравится +10 Проголосовать: не нравится

let us call the range [ l, r ] build the prefix sum array for the given array, let us call it B (B[0]=0 for empty prefix)

now
B[i] - B[j] where 0 ≤ j < i
gives all the sums of subarrays that end in ith element

So, in order for the sum of subarray [ j + 1...i ] to be between l and r the following should be true:

l ≤ B[i] - B[j] ≤ r
=>
l - B[i] ≤  - B[j] ≤ r - B[i]
=>
B[i] - l ≥ B[j] ≥ B[i] - r

so for each B[i], we should find the number of B[j] s that are in the previous range and j < i, which is done in a segment tree

total complexity: O(nlogn)

NOTE If the values are all positive you can use binary search for O(nlogn)