Largest Permutation Discussions | Algorithms | HackerRank

Largest Permutation

  • + 0 comments

    My Java solution with linear time and space complexity:

    public static List<Integer> largestPermutation(int k, List<Integer> arr) {
            if(arr.size() == 1) return arr; //no permutations possible
            
            //get the indices of each val in arr
            Map<Integer, Integer> valMap = new HashMap<>();
            for(int i = 0; i < arr.size(); i++) valMap.put(arr.get(i), i);
            
            //store the max val as size of arr
            int max = arr.size(), j = 0;
            
            //iterate through the arr and do k permutations
            while(j < arr.size() && k > 0){
                if(arr.get(j) != max){
                    int temp = arr.get(j);
                    arr.set(j, max);
                    arr.set(valMap.get(max), temp);
                    valMap.put(temp, valMap.get(max));
                    k--;
                }
                max--;
                j++;
            }
            return arr;
        }