Computer >> Computer tutorials >  >> Programming >> C++

Largest permutation after at most k swaps in C++


In this tutorial, we are going to write a program that finds the largest permutation after at most k swaps.

Let's see the steps to solve the problem.

  • Initialise the array.
  • Initialise an array to store the index with size n + 1.
  • Iterate over the array and store the index of each element in the position array.
  • Write a loop that iterate till n and k is greater than 0.
    • Store the position of n - i element in a temp variable.
    • Update position of current element arr[i] with position[n - i].
    • Update the position position[n - i] with current index i.
    • Swap the current element arr[i] with arr[temp. Decrement k.
  • Print the array elements.

Example

Let's see the code.

#include <bits/stdc++.h>
using namespace std;
void getLargestPermutation(int arr[], int n, int k) {
   int position[n + 1];
   for (int i = 0; i < n; ++i) {
      position[arr[i]] = i;
   }
   for (int i = 0; i < n && k; ++i) {
      if (arr[i] == n - i) {
         continue;
      }
      int temp = position[n - i];
      position[arr[i]] = position[n - i];
      position[n - i] = i;
      swap(arr[temp], arr[i]);
      --k;
   }
}
int main() {
   int arr[] = { 5, 3, 2, 6, 7, 1, 4 };
   int n = 7, k = 3;
   getLargestPermutation(arr, n, k);
   for (int i = 0; i < n; ++i) {
      cout << arr[i];
   }
   cout << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

7653214

Conclusion

If you have any queries in the tutorial, mention them in the comment section.