-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Expand file tree
/
Copy pathAggressiveCows.java
More file actions
66 lines (51 loc) · 1.4 KB
/
AggressiveCows.java
File metadata and controls
66 lines (51 loc) · 1.4 KB
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
/*
Time Complexity = O(N * log(N))
Space Complexity = O(log(N))
Where N is the number of elements in the given array/list.
*/
import java.util.Arrays;
public class AggressiveCows
{
// check if a distance of x is possible b/w each cow
private static boolean check(int x, int k, int []stalls)
{
// Greedy approach, put each cow in the first place you can.
int cowsPlaced = 1, lastPos = stalls[0];
int n = stalls.length;
// Traverse through the array stalls
for (int i = 1; i < n; i++)
{
if ((stalls[i] - lastPos) >= x)
{
cowsPlaced = cowsPlaced + 1;
if (cowsPlaced == k)
{
return true;
}
// Assign current position of stall as the lastPos.
lastPos = stalls[i];
}
}
return false;
}
public static int aggressiveCows(int []stalls, int k)
{
Arrays.sort(stalls);
// binary search
int low = 0, high = 1000000000, mid, pos = 0;
while (high >= low)
{
mid = (high + low) / 2;
if (check(mid, k, stalls))
{
low = mid + 1;
pos = mid;
}
else
{
high = mid - 1;
}
}
return pos;
}
}