is there any optimized way to do that q
I am getting TLE
#include<bits/stdc++.h>
using namespace std;
void swapfn(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
int srch(int a[],int k,int n,int temp)
{
for(int j=k;j<n;j++)
{
if(a[j]==temp)
{
return j;
}
}
}
bool comp(int a,int b)
{
return a>b;
}
int main()
{
int n,key;
cin>> n>> key;
int a[n];
for(int i=0;i<n;i++)
cin>> a[i];
unordered_map<int,int> mp;
for(int i=0;i<n;i++)
{
mp[a[i]]=i;
}
for(int i=0;i<n;i++)
{
if(a[i]!=n-i and key>0)
{
swap(a[i],a[mp.find(n-i)])
}
}
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
}
/*
5 2
3 4 1 2 5
*/
this code doesnot work…
please as soon as possible…
Hey please share your code on ide
Hey @sunneykumar309
Here is the updation you need to do in your code:
if(a[i]!=n-i and key>0)
{
swap(a[i],a[mp[n-i]]);
mp[a[mp[n-i]]]=mp[n-i];
key–;
}
key-- because we can only do key swaps
and 2nd line is for updating new index value of the element which was swapped.

