Largest Permutation Discussions | Algorithms | HackerRank

Largest Permutation

  • + 0 comments

    Java:

    public static List<Integer> largestPermutation(int k, List<Integer> arr) {
      int n = arr.size();
      int max = n;
      int[] indexMap = new int[max + 1];
    
      for (int i = 0; i < n; i++) {
        indexMap[arr.get(i)] = i;
      }
    
      for (int i = 0; i < n && k > 0; i++) {
        int currentValue = arr.get(i);
        int targetValue = n - i;
        if (currentValue != targetValue) {
          int targetIndex = indexMap[targetValue];
          arr.set(targetIndex, currentValue);
          arr.set(i, targetValue);
          indexMap[currentValue] = targetIndex;
          indexMap[targetValue] = i;
          k--;
        }
      }
      return arr;
    }