Difference Array
Assume we have an array A
of size N
, and given a list of updates of length K
, each of which is in the form of [from, to, diff]
which means adding diff
to all elements with indexes in range [from, to]
.
For example:
The brute force way is to visit all elements in range [from, to]
and add diff
to them for each update. It will take O(NK)
time.
We can improve this by using difference array, i.e. only storing the delta value at break points. Let delta[i]
be U[i] - U[i-1]
where U[i]
is the sum of all diff
s to A[i]
.
For update[i] = [from, to, diff]
, we do:
delta[from] += diff
delta[to+1] -= diff
So in the end we just need to traverse delta
array to recover the U
array.
Problems
Last updated