-
Notifications
You must be signed in to change notification settings - Fork 222
/
largest-permutation.py
38 lines (28 loc) · 1.02 KB
/
largest-permutation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/bin/python3
import sys
def largestPermutation(k, arr):
maxcur = max(arr)
positions = {}
for ind in range(len(arr)):
positions[arr[ind]] = ind
for ind in range(len(arr)):
if k == 0:
break
if arr[ind] == maxcur:
maxcur -= 1
if arr[ind] < maxcur:
#print("arr: {} pos: {}".format(arr, positions.items()))
mind = positions[maxcur]
positions[maxcur], positions[arr[ind]] = positions[arr[ind]], positions[maxcur]
arr[ind], arr[mind] = arr[mind], arr[ind]
#print("{} <-> {}".format(positions[maxcur], positions[arr[ind]]))
maxcur -= 1
k -= 1
#print("arr: {} pos: {}".format(arr, positions.items()))
return arr
if __name__ == "__main__":
n, k = input().strip().split(' ')
n, k = [int(n), int(k)]
arr = list(map(int, input().strip().split(' ')))
result = largestPermutation(k, arr)
print (" ".join(map(str, result)))