Why is this code giving wrong answer?

#include
#include
#include
using namespace std;
int main()
{int t,n,m,s[5000];
long long int d=1000000000;
cin>>t;
while(t>0)
{cin>>m;
n=m;
while(n>0)
{cin>>s[n-1];
n–;}
sort(s,s+m-1);
while(m>0)
{if(d>abs((s[m-1]-s[m-2])))
d=abs(s[m-1]-s[m-2]);
m–;}
cout<<d<<"\n";
t–;
}
}

There are many reasons why your solution is wrong:

  • The size of the array s is m, so the sort function should be sorting from s to s + m.
  • The value of d has to be renewed to 10^9 after every iteration, otherwise the solution is only valid for the first test case. By the way, it does not need to be long long int.
  • The loop that finds the minimum difference must run only while m > 1, otherwise s[m - 2] will cause an error when m equals 1.

Link to fixed solution: https://www.codechef.com/viewsolution/19417226

I hope this helps.