Skip to content

Instantly share code, notes, and snippets.

@maehrm
Created January 20, 2026 08:09
Show Gist options
  • Select an option

  • Save maehrm/f6d007989bc0564dd32a7319e6316524 to your computer and use it in GitHub Desktop.

Select an option

Save maehrm/f6d007989bc0564dd32a7319e6316524 to your computer and use it in GitHub Desktop.
N = int(input())
P = list(map(int, input().split()))
# (1) 末尾の昇順区間を探す
i = N - 1
while i > 0 and P[i - 1] < P[i]:
i -= 1
# (2) jは、昇順の始まりのひとつ左(交換対象)
j = i - 1
# (3) 交換対象を探す
k = i
while k < N and P[j] > P[k]:
k += 1
k -= 1
# (4) 交換
P[j], P[k] = P[k], P[j]
# (5) 右側を降順に
P[j + 1 :] = P[:j:-1]
print(*P)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment