# [Codeforces]- Help needed in Puzzles(337A) problem.

Here is my code. I have understood how to solve this using tutorial approach, but I want to know why my code is giving a WA and what changes should I make to get it accepted.

YOU GUYS ARE A CHARM. THANKS IN ADVANCE…

``````// JUST LIKE ANIMALS !!!!

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int main(){
int n,m;cin>>n>>m;vector<int> v(n+2);
int i,ans=INT_MAX,mini,maxi;
for(i=0;i<m;i++)cin>>v[i];
for(i=0;(m-n?i<m-n:i<1);i++){
maxi=*max_element(&v[i],&v[i+n]);
mini=*min_element(&v[i],&v[i+n]);
ans=min(maxi-mini,ans);
}
cout<<ans;
return 0;
}
``````

The accepted solution after corrections as suggested by @mukul_chandel.

``````// JUST LIKE ANIMALS !!!!

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int main(){
int n,m;cin>>n>>m;vector<int> v(m+2);
int i,ans=1001,mini,maxi;
for(i=0;i<m;i++)cin>>v[i];
sort(&v[0],&v[m]);
for(i=0;i<=m-n;i++){
maxi=*max_element(&v[i],&v[i+n]);
mini=*min_element(&v[i],&v[i+n]);
ans=min(maxi-mini,ans);
}
cout<<ans;
return 0;
}``````
1 Like
• size of vector should be m.
• no point of applying this algorithm without sorting. After sorting you can also find min and max without even using max_element() and min_element() which will also give your solution a better time complexity.
• Here is your corrected solution.
1 Like

#include<stdio.h>

void bubbleSort(int numbers[], int array_size)
{
int i, j, temp;

for (i = (array_size - 1); i >= 0; i–)
{
for (j = 1; j <= i; j++)
{
if (numbers[j-1] > numbers[j])
{
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
}
}

int main()
{
int a,b,x;
scanf("%d %d",&a,&b);
int ar[b];
for(x=0;x<b;x++)
{
scanf("%d",&ar[x]);
};

`````` bubbleSort(ar,b);

int min=ar[a-1]-ar[0];
for(x=0;x<b-a+1;x++)
{
if ((ar[a-1+x]-ar[x])<min) min=(ar[a-1+x]-ar[x]);
};

printf("%d",min);

return 0;
``````

}

My solution for the avove problem in c

Here is my solution to this problem.

@mukul_chandel , Thanks for helping me out but your solution is done using the tutorial approach and I wanted to done it using mine. I was just doing a boo-boo which you pointed out. Thanks I will be adding my accepted solution too .

1 Like