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;
}