Codingame: Horse-racing Duals
Original Problem
The Goal
Casablanca’s hippodrome is organizing a new type of horse racing: duals. During a dual, only two horses will participate in the race. In order for the race to be interesting, it is necessary to try to select two horses with similar strength.
Write a program which, using a given number of strengths, identifies the two closest strengths and shows their difference with an integer (≥ 0).
Game Input
Input
Line 1: Number N of horses
The N following lines: the strength Pi of each horse. Pi is an integer.
Output
The difference D between the two closest strengths. D is an integer greater than or equal to 0.
Constraints
1 < N < 100000
0 < Pi ≤ 10000000
Java Solution
class Solution { public static void main(String args[]) { Scanner in = new Scanner(System.in); int N = in.nextInt(); int answer = 0; int[] strength = new int[N]; Integer diff = Integer.MAX_VALUE; for (int i = 0; i < N; i++) { int pi = in.nextInt(); strength[i] = pi; } Arrays.sort(strength); for (int i = 0; i < strength.length - 1; i++) { if (diff > Math.abs(strength[i] - strength[i + 1])) { diff = Math.abs(strength[i] - strength[i + 1]); answer = diff; } } System.out.println(answer); } }