illumeow
Given an 1-based interger array $A$ of size $n$, there are $m$ operations. Each operation consists two number $1 \le l \le r \le n$ and an integer $x$, which means that all elements in $[l, r]$ should add $x$. After all operations, output the final array.
Just use a for loop to apply each operation.
Too slow for large $n, m$ !
Observe each operation, we can see many elements are updated multiple times.
Figure 1: Example of three range-add operations overlapping on a 12-element array.
Define the difference array $D$ of array $A$ as follows: $$D[i] = A[i] - A[i-1], \quad \text{for } i=2,3,\ldots,n$$ where we define $D[1] = A[1]$ for convenience.
We can recover $A$ from $D$ by: $$A[i] = D[1] + D[2] + \cdots + D[i], \quad \text{for } i=1,2,\ldots,n$$ which is the prefix sum of $D$.
A = [-7, 6, 9, 4, 3, -3, -6, -7]
D = [-7, 13, 3, -5, -1, 0, -3, -1]
To add $x$ to all elements in $[l, r]$ of $A$, we can do:
Why? After recovering $A$ from $D$: