Minimum Absolute Difference in an Array

HeeSeong·2021년 6월 29일
0

HackerRank

목록 보기
17/18
post-thumbnail

🔗 문제 링크

https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=greedy-algorithms


❔ 문제 설명


The absolute difference is the positive difference between two values a and b, is written |a-b| or |b-a| and they are equal. If a=3 and b=2, |3-2| = |2-3| = 1. Given an array of integers, find the minimum absolute difference between any two elements in the array.

Example.

arr = [-2,2,4]

There are 3 pairs of numbers:[-2,-2], [-2,4] and [2,4]. The absolute differences for these pairs are |(-2) - 2| = 4, |(-2) - 4| = 6 and . |2 - 4| = 2. The minimum absolute difference is 2.

Function Description

Complete the minimumAbsoluteDifference function in the editor below. It should return an integer that represents the minimum absolute difference between any pair of elements.

minimumAbsoluteDifference has the following parameter(s):

  • int arr[n]: an array of integers

Returns

  • int: the minimum absolute difference found

Input Format

The first line contains a single integer n, the size of arr.
The second line contains n space-separated integers, arr[i].


⚠️ 제한사항


  • 2n1052 ≤ n ≤ 10^5

  • 109arr[i]109-10^9 ≤ arr[i] ≤ 10^9



💡 풀이 (언어 : Java)


간단한 문제이다. 자바에서 절대값을 구할때는 Math.abs()를 사용하면 된다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
	private static int minimumAbsoluteDifference(int[] arr) {
		int min = 2000000000;
		Arrays.sort(arr);
		for (int i = 0; i < arr.length-1; i++) {
			min = Math.min(min, Math.abs(arr[i] - arr[i+1]));
		}
		return min;
	}

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		int[] arr = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
		System.out.println(minimumAbsoluteDifference(arr));
		br.close();
	}
}
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글