(Hacker Rank) Max Min - Solution

Link to the problem: https://www.hackerrank.com/challenges/angry-children

The solution below sorts the given array and, for every interval of size K, we check its unfairness. In addition, we keep always the minimum value of unfairness.


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

public class Solution {
   
   public static void main(String[] args) throws NumberFormatException, IOException {

      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      int N = Integer.parseInt(br.readLine());
      int K = Integer.parseInt(br.readLine());
      int[] list = new int[N];

      for(int i = 0; i < N; i++) {
         list[i] = Integer.parseInt(br.readLine());
      }
    
      int unfairness = Integer.MAX_VALUE;
      Arrays.sort(list);
      for (int i = 0; i <= N-K; i++) {
          int min = list[i];
          int max = list[i+K-1];
          unfairness = Math.min(unfairness, max-min);
      }
    
      System.out.println(unfairness);
   }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução