DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord account linking.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Sorting a Sequence 4

Back to problem

Editorial

Let xix_ixi​ be the number of times index iii is chosen. The total number of operations is subtracted from every element, so it does not affect sortedness. We require Ai+2xi≤Ai+1+2xi+1A_i+2x_i\leq A_{i+1}+2x_{i+1}Ai​+2xi​≤Ai+1​+2xi+1​. Start with x1=0x_1=0x1​=0 and choose xi=max⁡(0,xi−1+⌈(Ai−1−Ai)/2⌉)x_i=\max(0,x_{i-1}+\lceil(A_{i-1}-A_i)/2\rceil)xi​=max(0,xi−1​+. Increasing an earlier choice cannot lower any later bound, so this greedy choice is optimal.

Each xix_ixi​ is at most 5⋅108+500005\cdot10^8+500005⋅108+50000, so the total number of operations is at most 5.0005⋅10135.0005\cdot10^{13}. 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

⌈(Ai−1​−
Ai​)/2⌉)
5.0005⋅
1013
O(N)O(N)O(N)