Advertisement
saurav_kalsoor

Roof Length - JAVA

Nov 19th, 2021
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.67 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Test {
  4.  
  5.     static Scanner sc = new Scanner(System.in);
  6.  
  7.     public static void main(String[] args) {
  8.  
  9.         int n = sc.nextInt();
  10.         int k = sc.nextInt();
  11.         int arr[] = new int[n];
  12.  
  13.         for(int i = 0; i < n; i++)
  14.             arr[i] = sc.nextInt();
  15.  
  16.         int res = roofLength(n, k, arr);
  17.         System.out.println(res);
  18.     }
  19.  
  20.     public static int roofLength(int n, int k, int[] cars) {
  21.         Arrays.sort(cars);
  22.         int res = cars[k-1] - cars[0] + 1;
  23.  
  24.         for(int i=1 ; i < n - k + 1; i++) {
  25.             res = Math.min(res, cars[k-1+i] - cars[i] + 1);
  26.         }
  27.  
  28.         return res;
  29.     }
  30. }
  31.  
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement