1+ import java .util .*;
2+
3+ public class AggressiveCows {
4+ public static void main (String [] args ) {
5+ Scanner sc = new Scanner (System .in );
6+ int test = sc .nextInt ();
7+ while (test -- > 0 ) {
8+ int n = sc .nextInt ();
9+ int cows = sc .nextInt ();
10+ int [] stalls = new int [n ];
11+ for (int i = 0 ; i < n ; i ++) {
12+ stalls [i ] = sc .nextInt ();
13+ }
14+ System .out .println (maxDistance (stalls , cows , n ));
15+ }
16+ sc .close ();
17+ }
18+
19+ private static int maxDistance (int [] stalls , int cows , int n ) {
20+ if (stalls == null || stalls .length == 0 ) {
21+ return 0 ;
22+ }
23+ Arrays .sort (stalls );
24+ int low = 1 ;
25+ int high = (int )(1e9 + 7 );
26+ int maxCowDistance = -1 ;
27+ while (low <= high ) {
28+ int middle = low + (high - low ) / 2 ;
29+ if (canCowBePlaced (stalls , cows , middle )) {
30+ maxCowDistance = middle ;
31+ low = middle + 1 ;
32+ }
33+ else {
34+ high = middle - 1 ;
35+ }
36+ }
37+ return maxCowDistance ;
38+ }
39+
40+ private static boolean canCowBePlaced (int [] stalls , int cows , int minDistance ) {
41+ int cowCount = 1 ;
42+ int previousPositionOfCow = stalls [0 ];
43+ for (int i = 1 ; i < stalls .length ; i ++) {
44+ int currentStallPos = stalls [i ];
45+ if (currentStallPos - previousPositionOfCow >= minDistance ) {
46+ cowCount ++;
47+ previousPositionOfCow = currentStallPos ;
48+ }
49+ }
50+ return cowCount >= cows ;
51+ }
52+ }
0 commit comments