Official

B - Products of Min-Max Editorial by evima


Let us set some order between elements with the same value and sort \(A\). \(A_i \times A_j\) \(\left(i < j\right)\) gets added to the answer \(2^{j-i-1}\) times, so the answer is:

\[ \sum_{i = 1}^N \sum_{j = i + 1}^N A_i \times A_j \times 2^{j-i-1} + \sum_{i = 1}^N A_i \times A_i \]

where

\[ \sum_{i = 1}^N \sum_{j = i + 1}^N A_i \times A_j \times 2^{j-i-1} \]

\[ = \sum_{i = 1}^N A_i \left(\sum_{j = i + 1}^N A_j \times 2^{j-i-1}\right) \tag{1} \]

and

\[ \left(\sum_{j = (i-1) + 1}^N A_j \times 2^{j-(i-1)-1}\right) = 2 \times \left(\sum_{j = i + 1}^N A_j \times 2^{j-i-1}\right) + A_i \]

Thus, we can compute (1) in descending order from \(i = N\) in \(O\left(N\right)\) time, so we can solve the problem in \(O\left(N\log N\right)\) time.

posted:
last update: