|
| 1 | +package com.hackerrank.interviewpreparation.greedyalgorithmns; |
| 2 | + |
| 3 | +import java.io.BufferedWriter; |
| 4 | +import java.io.FileWriter; |
| 5 | +import java.io.IOException; |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.Scanner; |
| 8 | + |
| 9 | +/** |
| 10 | + * @author rpatra16 |
| 11 | + * @since 04/11/2018 |
| 12 | + */ |
| 13 | +public class MinimumAbsoluteDifference { |
| 14 | + |
| 15 | + /** |
| 16 | + * Finds the minimum absolute difference in the array. |
| 17 | + * |
| 18 | + * @param a input array |
| 19 | + * @return the minimum absolute difference between any two different elements in the array a |
| 20 | + */ |
| 21 | + static int minimumAbsoluteDifference(int[] a) { |
| 22 | + int minDiff = Integer.MAX_VALUE, diff; |
| 23 | + Arrays.sort(a); |
| 24 | + for (int i = 0; i < a.length - 1; i++) { |
| 25 | + if ((diff = Math.abs(a[i] - a[i + 1])) < minDiff) { |
| 26 | + minDiff = diff; |
| 27 | + } |
| 28 | + } |
| 29 | + return minDiff; |
| 30 | + } |
| 31 | + |
| 32 | + private static final Scanner scanner = new Scanner(System.in); |
| 33 | + |
| 34 | + public static void main(String[] args) throws IOException { |
| 35 | + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); |
| 36 | + |
| 37 | + int n = scanner.nextInt(); |
| 38 | + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); |
| 39 | + |
| 40 | + int[] arr = new int[n]; |
| 41 | + |
| 42 | + String[] arrItems = scanner.nextLine().split(" "); |
| 43 | + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); |
| 44 | + |
| 45 | + for (int i = 0; i < n; i++) { |
| 46 | + int arrItem = Integer.parseInt(arrItems[i]); |
| 47 | + arr[i] = arrItem; |
| 48 | + } |
| 49 | + |
| 50 | + int result = minimumAbsoluteDifference(arr); |
| 51 | + |
| 52 | + bufferedWriter.write(String.valueOf(result)); |
| 53 | + bufferedWriter.newLine(); |
| 54 | + |
| 55 | + bufferedWriter.close(); |
| 56 | + |
| 57 | + scanner.close(); |
| 58 | + } |
| 59 | +} |
0 commit comments