DOJ logoDOJ
Problems
Recently added problemsSaved problems
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-backed certification.

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

Replacement

Back to problem

Editorial

Every order of operations has the same total cost. The answer is

∑i=1NPi−min⁡1≤i≤NPi.\sum_{i=1}^{N}P_i-\min_{1\leq i\leq N}P_i.i=1∑N​Pi​−1≤i≤Nmin​Pi​.

Compute the sum and minimum in one pass. The time complexity is O(N)O(N)O(N) and the additional space complexity is O(1)O(1)O(1).

Proof

Replacing adjacent values x,yx,yx,y with min⁡(x,y)\min(x,y)min(x,y) decreases the sum of the sequence by

x+y−min⁡(x,y)=max⁡(x,y),x+y-\min(x,y)=\max(x,y),x+
y
−
min(x,y)=
max(x,y),

which is exactly the cost of the operation.

The total cost therefore equals the initial sum minus the final remaining value. Regardless of the order of operations, that value is the minimum of the original sequence, giving the formula above.