D - 1 or 2 Editorial by evima


Assume that we can only choose to eat two candies at a time, and the total number of candies is even.

Then, we can show that an optimal solution eats the candy with the \(i\)-th highest tastiness and the one with the \(i\)-th lowest tastiness together. This is because \(\max(A+D,B+C) \leq \max(A+C,B+D)), \min(A+C,B+D) \leq \min(A+D,B+C)\) holds for four integers \(A\), \(B\), \(C\), and \(D\) such that \(A \leq B \leq C \leq D\).

Eating one candy \(x\) is equivalent to adding a candy with the tastiness of \(0\) and then eating it together with \(x\). From this, we can reduce the original problem to the version above.

Therefore, we can solve the original problem by finding the smallest answer to the problem above when we add between \(0\) and \(N\) candies of the tastiness of \(0\). It can be done in \(O(N^{2})\) time, which is fast enough.

posted:
last update: