Every move transfers one candy, so the total remains .
Sort the final counts as . They are nonnegative integers, so .
Their total is therefore at least
If is smaller than this, the goal is impossible. Equivalently, output when .
For the remaining pages, assume and write . This condition guarantees . We will show that the goal is possible and find its minimum cost.