简体   繁体   中英

Maximum number after K swaps using recursion

I have to make a function maximize(x,k) in which x is an integer and k is the maximum number of swaps and output the maximum number after doing maximum k swaps. Also two functions swap(s,i,j) and sort(s) are to be used which as the name suggests swap the characters of a string according to the index and sorts from highest to lowest respectively. I tried but cannot do it without having another variable i in the maximize function. Is there any way it can be done without the variable i in the maximize function by just passing two variable x and k. Here is my code:

def swap(s,i,j):
    return s[0:i]+s[j]+s[i+1:j]+s[i]+s[j+1:len(s)]

def sort(s):
    return "".join((sorted(s)[::-1]))

def maximize(x,k,i):
    if k==0 or i==len(str(x)):
        return x

    s=str(x)
    t=sort(s)

    if t[i]>s[i]:
        j=s.find(t[i],i,len(s))
        s=swap(s,i,j)
        return maximize(int(s),k-1,i+1)
    else:
        return maximize(int(s),k,i+1)

print(maximize(223953,2,0))

To get the highest possible number you need to have the biggest digits up front. this means that each layer of recursion can focus on placing the first digit and rely on the next levels for swapping of the remaining ones.

def swap(s,i,j):
    return s[0:i]+s[j]+s[i+1:j]+s[i]+s[j+1:len(s)]

def sort(s):
    return "".join((sorted(s)[::-1]))

def maximize(x,k):
    if not k or x<10: return x   # stop when no more swaps or no more digits
    s = str(x)
    if s == sort(s): return x    # stop if already at max value
    i = s.index(max(s))          # find position of highest digit
    if i>0: s = swap(s,0,i)      # swap if not already first
    suffix = maximize(int(s[1:]),k - (i>0)) # recurse for rest of digits (don't reduce swap count if no swap done)
    return int(s[0]+str(suffix)) # combine biggest digit with maximized remainder

print(maximize(223953,2)) # 953223

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM