Count of Range Sum

Given an integer arraynums, return the number of range sums that lie in[lower, upper]inclusive. Range sumS(i, j)is defined as the sum of the elements innumsbetween indicesiandj(ij), inclusive.

Note: A naive algorithm ofO(n2) is trivial. You MUST do better than that.

Example:

Input: nums = [-2,5,-1], lower = -2, upper = 2,
Output: 3 
Explanation: The three ranges are : [0,0], [2,2], [0,2] and their respective sums are: -2, -1, 2.

分析

Sum[k] is the sum of first k numbers. O(N^2) solution is

for j in range(n + 1):
    for i in range(j):
        if lower <= Sum[j] - Sum[i] <= upper: res += 1
This is equal to:

collection = empty
for sum_j in Sum:
    sum_i_count = how many sum_i in this collection that sum_j - upper <= sum_i <= sum_j - lower
    res += sum_i_count
    put sum_j into this collection

算presum,然后遍历sum来Update bitTree,这里用的Index是该sum在sorted后sum arr的index。每加入一个sum,就提高该sum和parent sum的权重。最后get就是权重相减。

分治法

presum数组分半,左右分治相加之后,计算跨越左右的部分。

固定左边在Mid前,右边i,j分别算max和min可达范围。左边固定点在[lo,mid]之间loop

segment tree 用sum 值范围, 不是Index做范围,count做val返回。对比前面直接Index建树,不是值范围。

query root在范围内直接返回root

记得update里要返回 min = max = val

Last updated

Was this helpful?