My issue
It says it fails for some testcases. Can someone explain how?
My code
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
int t{};
cin>>t;
int n,k;
while(t--)
{
cin>>n>>k;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
for (int i = 0; i < n; i++)
{
for (int j = i+k; j < n; j+=k)
{
if (a[i]>a[j])
{
int temp = a[i];
a[i] = a[j];
a[j]=temp;
}
}
}
for (int i = 0; i < n; i++)
cout<<a[i]<<" ";
cout<<endl;
}
return 0;
}
Problem Link: SWAPNUM31 Problem - CodeChef
@divyanshum3232
For the smaller values of K your code will touch n^2 complexity which is not allowed.
if u observe it carefully u will se for k<=n/2 u will be able to rearrange the elements in any order u want.
Thus for k<=n/2 the answer would be sorted array.
and for k>n/2 u will not able to rearrange the elements between n-k to k index and rest of the element can be sorted.
thats the whole logic
This is my code i hope u will get it.
include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t–)
{
int n,k;
cin>>n>>k;
int a[n];
vector v;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
if(n>=2*k)
{
sort(a,a+n);
}
else
{
for(int i=0;i<n;i++)
{
if(i>=k||i<n-k)
{
v.push_back(a[i]);
}
}
sort(v.begin(),v.end());
int j=0;
for(int i=0;i<n;i++)
{
if(i>=k||i<n-k)
{
a[i]=v[j];
j++;
}
}
}
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
}