Largest Permutation Discussions | Algorithms | HackerRank

Largest Permutation

  • + 0 comments

    Ruby

    def largestPermutation(k, arr)    
        array_swap = Array.new(arr.length)   
        arr.length.times { |i| array_swap[arr[i]] = i}        
        arr.length.times do |i|
            next if arr[i] == arr.length-i
            if k > 0
                index_change = array_swap[arr.length-i]
                array_swap[arr[i]] = index_change
                arr[i], arr[index_change] = arr[index_change], arr[i]    
                k -= 1
            end        
        end
        arr    
    end