Let be the number of times index is chosen. The total number of operations is subtracted from every element, so it does not affect sortedness. We require . Start with and choose . Increasing an earlier choice cannot lower any later bound, so this greedy choice is optimal.
Each is at most , so the total number of operations is at most . Thus the exact answer fits in a signed 64-bit integer. Handle ceiling division for negative differences correctly. The time complexity is .
Solution written by GPT6