Unlock time limit exceed

/*
Shekhar is a bomb defusal specialist. He once encountered a bomb that can be defused only by a secret code. He is given a number N and a number K. And he is also given permutation of first N natural numbers . The defusal code is the largest permutation possible by doing atmost K swaps among a pair of the given permutation. Help him to find the final permutation.

Input Format
First line contains ​an integer N and an integer k. The next line contains N space separated integers denoting the given permutation.

Constraints
1 <= n <= 10^5 1<= K <= 10^9

Output Format
The final permutation of the numbers with every number separated by a space with other number.

Sample Input
5 2
3 4 1 2 5
Sample Output
5 4 3 2 1
Explanation
First we can swap 5 with 3 which gives us 5 4 1 2 3 and then we can swap 3 and 1 which gives us 5 4 3 2 1.
*/

#include
#include
#include

using namespace std;

int main()
{
int n,k;
cin >> n>> k;
vector arr;
for(int i=0,x; i<n; i++){
cin >> x ;
arr.push_back(x);//input the number array
}
while(k>0)
{
for(int i=0; i<n; i++){
for(int j=i; j<n; j++){
if(arr[j] > arr[i])
{
iter_swap(arr.begin() + i, arr.begin() + j);
k–;
}
}
}
}
for(auto x:arr)
{
cout<<x <<" “;
}
cout<<”\n";
}

How do i approach this problem in a more eficient way?
and is my current approach good for the right answer?

hello @akshpreetsinghs

no there is slight mistake in ur approach.

decrement k only once after finding maximum.
code implementation for ur logic ->

use hashing .

The hint to solve the problem is that the given array will always contain permutation of the first N natural numbers. So we will prepare a map which will contain element as the key and the index at which it is present as the value.

Algorithm

  1. Create the map by filling the number as the key and the index at which it is present as the value
  2. Iterate over the whole array.
  3. For element at a particular index m we will check if it is present at its best spot or not.
  4. The best spot of any number num is the N-num index of the array.
  5. If the number is not present at its best spot then we will swap the number with element present at that spot.
  6. As we have stored the index of every element in the map we can easily retrieve that from the map to get the swap done.
    https://ide.codingblocks.com/s/387865

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.