Horses...NZEC error

enter code here
import java.io.;
import java.util.
;

class horses{

public static void main(String[] args) throws java.lang.Exception
{
	
	BufferedReader r= null;
	
	try
	{	

		r= new BufferedReader(new InputStreamReader(System.in));
		int	T= Integer.parseInt(r.readLine());		//no. of test cases
	
		if(T < 1 || T > 10)
			System.exit(0);
		else
		{
			for(int i=1; i<=T; i++)
			{
				int N= Integer.parseInt(r.readLine());//no. of horses 

				if(N < 2 || N > 5000)
					System.exit(0);
				else
				{
					String[] arr= r.readLine().split(" ");
					int[] horse_no= new int[arr.length];	  				
					int temp, diff;

					for (int j=0; j<N; j++)
					{		
						horse_no[j]= Integer.parseInt(arr[j]); 
						if(horse_no[j]<0)
							System.exit(0);
					}

					Arrays.sort(horse_no);
					diff= horse_no[1]-horse_no[0];

					for(int j=0; j<N-1; j++)
					{
						for(int k=j+1; k<N; k++)
						{
							if(diff>(horse_no[k]-horse_no[j]))
							diff= horse_no[k]-horse_no[j];
						}
					}

					System.out.println(diff);
					
				}	
			}
		}
	}
	catch(IOException e){
		e.printStackTrace();
	}
	
	finally{
		if(r!= null)
			r.close();
	}

}

}

i have tried everything with this program but my code is still showing an NZEC runtime error, can anyone point out the error…

In codechef,you need to use Main as the class name so replace class horses with public static Main and it should work!
Btw, there is no need to close the BufferedReader object… so try removing that line.

thanks “goodfornothing”, that really worked, but my program is taking about 9 seconds to execute, how can i make my program to run in a shorter span of time, i mean what changes can i make???

Take a close look at your program. You sort the array to make sure that every element is a neighbour of the elements that differ the least, but then you compare each combination of two entries. It seems like you are combining two different strategies to solve the problem, which makes the result slower.

1 Like

procoder,

As renze pointed out your code runs slow, as you are combining 2 different (but both correct) approaches to solve the problem…

If the array is sorted, do you think you need to test ALL pairs of elements? :wink:

I hope this gets you on the right track, to improve code speed :smiley:

PS: Also, if you could provide me what kind of java version and/or JVM you have installed I’d be very appreciated :slight_smile:

Bruno