Largest Permutation Discussions | Algorithms | HackerRank

Largest Permutation

  • + 0 comments
    def largestPermutation(k, arr):
        n = len(arr)
        position_map = {value: idx for idx, value in enumerate(arr)}
        
        current_max = max(arr)
        for i in range(n):
            if k == 0:
                break
            
            if arr[i] != current_max:
                # Swap arr[i] and current_max
                arr[position_map[current_max]], arr[i] = arr[i], current_max
                # Update position_map
                position_map[arr[position_map[current_max]]] = position_map[current_max]
                position_map[current_max] = i
                # Decrement k
                k -= 1
            
            # Update current_max to the next largest number
            current_max -= 1
        
        return arr