MCPcopy Create free account
hub / github.com/MohamedMetwalli5/HackerRank-Solutions / MaxMin

Class MaxMin

ProblemSolving (General)/MaxMin.java:9–53  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7import java.util.regex.*;
8
9public class MaxMin {
10
11 // Complete the maxMin function below.
12 static int maxMin(int k, int[] arr) {
13 int min = Integer.MAX_VALUE;
14 Arrays.sort(arr);
15 for(int i=0;i+k-1<arr.length;i++){
16 if(arr[i+k-1] - arr[i] < min){
17 min = arr[i+k-1] - arr[i];
18 }
19 }
20
21 return min;
22
23 }
24
25 private static final Scanner scanner = new Scanner(System.in);
26
27 public static void main(String[] args) throws IOException {
28 BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
29
30 int n = scanner.nextInt();
31 scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
32
33 int k = scanner.nextInt();
34 scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
35
36 int[] arr = new int[n];
37
38 for (int i = 0; i < n; i++) {
39 int arrItem = scanner.nextInt();
40 scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
41 arr[i] = arrItem;
42 }
43
44 int result = maxMin(k, arr);
45
46 bufferedWriter.write(String.valueOf(result));
47 bufferedWriter.newLine();
48
49 bufferedWriter.close();
50
51 scanner.close();
52 }
53}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected