Largest Permutation Discussions | Algorithms | HackerRank

Largest Permutation

  • + 0 comments

    Here is my c++ solution O(n), you also have a vidéo explanation here : https://youtu.be/baZOM6KLSWM

    vector<int> largestPermutation(int k, vector<int> arr) {
        map<int, int> indexes;
        for(int i = 0; i < arr.size(); i++) indexes[arr[i]] = i;
        
        int Mx = arr.size(), position = 0;
        while(k && position < arr.size()){
            if(arr[position] != Mx){
                int temps = arr[position];
                arr[position] = Mx;
                arr[indexes[Mx]] = temps;
                k--;
                indexes[temps] = indexes[Mx];
            }
            Mx--;
            position++;
        }
        
        return arr;
    }