Largest Permutation Discussions | Algorithms | HackerRank

Largest Permutation

  • + 0 comments

    Python3

    def largestPermutation(k, arr):
        # Write your code here
            
        n = len(arr) 
        D =  { v:k for k,v in enumerate(arr) } # dict lookup >>> arr.index()
        
        c = 0
        for i in range(n): 
            if arr[i]!=n-i:  # In sorted array, n-i should be at index i
                D[arr[i]] = D[n-i] # if not then update indexes
                arr[i],arr[D[n-i]]=n-i,arr[i] # do swap
                c = c + 1
    
            if c == k: #break if runs out of swaps
                break
        return arr