Sum of distances between points on one-dimensional axis We have given integer array of $n$ points, let it be $A$, showing where it is on the x-axis. For this problem we are working only with the x-axis and the y-axis is not important at all. Now for given two indexes $l$ and $r$, such that $0\leq l\leq r \leq n-1$, we want to find the sum of distances from each point whose index is in the range $l, r$ to the point with index $r$.

For example $A = \{1, 2, 4, 6, 8\}$ and $l = 0$, $r = n-1$ The output should be $(8-8) + (8-6) + (8-4) + (8-2) + (8-1) = 0 + 2 + 4 + 6 + 7 =19$

I know that it can be implemented in $O(1)$ after $O(N)$ preprocessing but I don't get the intuition behind that, and the formula is very unclear to me.
Let us start with the formula for the sum of distances:
$$
\begin{align*}
D(\ell,r) := \sum_{i=\ell}^r [A_r - A_i] &amp;= (r-\ell+1) A_r - \sum_{i=\ell}^r A_i \\ &amp;= (r-\ell+1) A_r - \sum_{i=1}^r A_i + \sum_{i=1}^{\ell-1} A_i.
\end{align*}
$$
In time $O(n)$ we can compute an array $B_i = \sum_{j=1}^i A_j$: indeed, $B_0 = 0$, and $B_j = B_{j-1} + A_j$. The formula above then translates to
$$
D(\ell,r) = (r-\ell+1)A_r - B_r + B_{\ell-1},
$$
which can be computed in $O(1)$.