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

The Last Remaining Number 2

Back to problem

Editorial

The answer is min⁡(A1,…,AN)+N−1\min(A_1,\ldots,A_N)+N-1min(A1​,…,AN​)+N−1.

Let mmm be the minimum just before an operation, and let xxx be the removed value. Every surviving value yyy falls into one of two cases:

  • If y≤xy\le xy≤x, it becomes y+1≥m+1y+1\ge m+1y+1≥m+1.
  • If y>xy>xy>x, it is unchanged. Since the values are integers and , we have .

Thus the minimum increases by at least one per operation. There are exactly N−1N-1N−1 operations, giving a lower bound of the initial minimum plus N−1N-1N−1.

To attain the bound, always remove a current maximum. Every remaining value is at most the removed value, so every one increases by one. A minimum occurrence remains: if removing a maximum also removes a minimum, all current values are equal and another occurrence remains. Consequently, the minimum increases by exactly one per operation and the bound is attained.

For N=1N=1N=1, no operation is performed and the same formula applies. The intended solution for the single subtask stores only the minimum while reading the input. Time is O(N)O(N)O(N) and auxiliary space is O(1)O(1)O(1).

The naive solution repeatedly finds and removes a maximum and updates every remaining value explicitly. It is correct but takes O(N2)O(N^2)O(N2) time and O(N)O(N)O(N) space, so it times out on maximum-size inputs.

Each integer increases at most N−1N-1N−1 times. The answer and all simulation values are at most 109+200 000−1=1 000 199 99910^9+200\,000-1=1\,000\,199\,999109+200000−1=1. All arithmetic fits signed 64-bit integers.

Solution written by GPT6

x≥mx\ge mx≥m
y≥x+1≥m+1y\ge x+1\ge m+1y≥x+1≥m+1
000
199
999