Let's denote prefix sum as Pi=a1+a2++ai{P_i = a_1 + a_2 + \dots + a_i} and suffix sum as Si=ai+ai+1++an{S_i = a_i + a_{i+1} + \dots + a_n}.

Now elaborate the given operation.

i=lkaij=praj| \sum\limits_{i = l}^{k} a_i - \sum\limits_{j = p}^{r} a_j |

=(al+al+1++ak)(ap+ap+1++ar){ = |(a_{l} + a_{l+1} + \dots + a_{k}) - (a_{p} + a_{p+1} + \dots + a_{r})|}

={(a1+a2++ak)(a1+a2++al1)}{(ap+ap+1++an)(ar+1+ar+2++an)}{ = |\{(a_1 + a_2 + \dots + a_k) - (a_1 + a_2 + \dots + a_{l-1})\} - \{(a_{p} + a_{p+1} + \dots + a_{n}) - (a_{r+1} + a_{r+2} + \dots + a_n)\}|}

=(PkPl1)(SpSr+1){ = |(P_k - P_{l-1}) - (S_p - S_{r+1})|}

=(PkSp)(Pl1Sr+1){ = |(P_k - S_p) - (P_{l-1} - S_{r+1})|}

Here, as Pl1P_{l-1} and Sr+1S_{r+1} are constant, the difference depends on PkP_k and SpS_p.

Mathematically, PkSp=max(PkSp,SpPk){|P_k - S_p| = max(P_k - S_p, S_p - P_k)}. So, the maximum difference can be found in two cases.

  1. PkSp{P_k - S_p} where PkP_k is maximum prefix sum and SpS_p is minimum suffix sum.

  2. SpPk{S_p - P_k} where SpS_p is maximum suffix sum and PkP_k is minimum prefix sum.

So, take the maximum and the minimum prefix sum and suffix sum in the range [l,r][l, r] and check which one gives the maximum difference.

Now, how can you find the maximum and the minimum prefix sum and suffix sum in the range [l,r][l, r]?

The answer is Segment Tree. Build a segment tree to find the maximum and the minimum prefix sum. And build another segment tree to find the maximum and the minimum suffix sum. Note that, in the segment trees, you have to keep the indices not the value. Complexity will be O(q×logn){O(q \times log n)}per testcase.

Statistics

64% Solution Ratio
AlfehsaniEarliest, Apr '22
fahimcp495Fastest, 0.0s
NirjhorLightest, 9.4 MB
sh2018331053Shortest, 1623B
Toph uses cookies. By continuing you agree to our Cookie Policy.