⬅ Previous Topic
Kth Missing Positive NumberNext Topic ⮕
Allocate Minimum Number of Pages⬅ Previous Topic
Kth Missing Positive NumberNext Topic ⮕
Allocate Minimum Number of PagesTopic Contents
Given N stalls represented by their positions on a number line (sorted or unsorted), and K cows to place in these stalls, the goal is to place the cows such that the minimum distance between any two cows is as large as possible.
K
cows in N
stalls.If the number of cows exceeds the number of stalls, it’s not possible to place all cows.
arr
in increasing order.low = 1
(smallest possible min distance) and high = arr[n - 1] - arr[0]
(largest possible).low ≤ high
:mid = (low + high) / 2
.k
cows with at least mid
distance between them.mid
as a candidate and try for a larger value (low = mid + 1
).high = mid - 1
).mid
found.import java.util.Arrays;
public class AggressiveCows {
public static boolean canPlace(int[] stalls, int cows, int minDist) {
int count = 1; // Place first cow at the first stall
int lastPlaced = stalls[0];
for (int i = 1; i < stalls.length; i++) {
if (stalls[i] - lastPlaced >= minDist) {
count++;
lastPlaced = stalls[i];
if (count == cows) return true;
}
}
return false;
}
public static int solve(int n, int k, int[] arr) {
Arrays.sort(arr);
int low = 1, high = arr[n - 1] - arr[0];
int result = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
if (canPlace(arr, k, mid)) {
result = mid; // Try for a bigger answer
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
public static void main(String[] args) {
int[] stalls = {1, 2, 4, 8, 9};
int k = 3;
System.out.println("Max Min Distance: " + solve(stalls.length, k, stalls));
}
}
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n log(maxDist)) | Binary search on the distance (log(max position)) and each check takes O(n). |
Average Case | O(n log(maxDist)) | Each iteration of binary search checks placement for given mid using O(n). |
Worst Case | O(n log(maxDist)) | In the worst case, binary search runs log(max distance) steps and each step scans the stalls. |
O(1)
Explanation: No extra space apart from a few variables; we sort in-place and use constant memory.
⬅ Previous Topic
Kth Missing Positive NumberNext Topic ⮕
Allocate Minimum Number of PagesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.