-
Notifications
You must be signed in to change notification settings - Fork 0
/
AGGRCOW.java
71 lines (55 loc) · 1.54 KB
/
AGGRCOW.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Problem link - https://www.spoj.com/problems/AGGRCOW/
// TC - O(n logn)
// SC - O(1)
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
//number of test cases
while(t-- > 0){
int n = sc.nextInt();
int c = sc.nextInt();
List<Integer> storeLocations = new ArrayList<>();
for(int store = 1; store <= n; store++){
storeLocations.add(sc.nextInt());
}
int maxMinDistance = findLargestMinDistance(n, c, storeLocations);
System.out.println(maxMinDistance);
}
}
public static int findLargestMinDistance(int n, int c, List<Integer> storeLocations){
int ans = 0;
// sort storeLocations ASC
Collections.sort(storeLocations);
//binary search
int s = 1, e = (storeLocations.get(n - 1) - storeLocations.get(0));
while(s <= e){
int mid = s + (e - s)/2;
if(coversAllStores(n, mid, c, storeLocations)){
s = mid + 1;
ans = mid;
} else {
e = mid - 1;
}
}
return ans;
}
public static boolean coversAllStores(int n, int minDist, int c, List<Integer> storeLocations){
//placing a cow at 1st stall
int lastCowPosition = storeLocations.get(0);
c--;
// starting from 2nd stall
for(int i = 1; i < n; i++){
int dist = storeLocations.get(i) - lastCowPosition;
if(dist >= minDist){
c--; //place a cow at this store
lastCowPosition = storeLocations.get(i);
}
}
return (c <= 0); // true if all cows are placed
}
}