Max and Min

Published on August 20, 2021
Last updated August 20, 2021

You will be given a list of integers,arr, and a single integer k. You must create an array of length k from elements of arr such that its unfairness is minimized. Call that array subarr. Unfairness of an array is calculated as max(subarr) - min(subarr).

Sample Input 0

7
3
10
100
300
200
1000
20
30

Sample Output 0

20

Solution in java

import java.util.Arrays;
import java.util.Scanner;

class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        int k = sc.nextInt();
        k--;
        int[] array = new int[size];
        for (int i = 0; i < size; i++) {
            array[i] = sc.nextInt();
        }
        Arrays.sort(array);
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < size - k; i++) {
            int unfairness = array[k + i] - array[i];
            if (unfairness < result) {
                result = unfairness;
            }
        }
        System.out.println(result);
        sc.close();
    }
}


Tags :