Given an array nums of size n, which denotes the positions of stalls, and an integer k, which denotes the number of aggressive cows, assign stalls to k cows such that the minimum distance between any two cows is the maximum possible. Find the maximum possible minimum distance.
Input: n = 6, k = 4, nums = [0, 3, 4, 7, 10, 9]
Output: 3
Explanation: The maximum possible minimum distance between any two cows will be 3 when 4 cows are placed at positions [0, 3, 7, 10]. Here the distances between cows are 3, 4, and 3 respectively. We cannot make the minimum distance greater than 3 in any ways.
Input : n = 5, k = 2, nums = [4, 2, 1, 3, 6]
Output: 5
Explanation: The maximum possible minimum distance between any two cows will be 5 when 2 cows are placed at positions [1, 6].
Input : n = 5, k = 3, nums = [10, 1, 2, 7, 5]
The extremely naive approach is to use linear search to check all possible distances from 1 to (max-min) where, max is the maximum element of the array and min is the minimum element of the array. The maximum distance for which the cows can be placed, will be our answer.
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
/* Function to check if we can place 'cows' cows
with at least 'dist' distance apart in 'stalls' */
bool canWePlace(vector<int> &nums, int dist, int cows) {
// Size of array
int n = nums.size();
// Number of cows placed
int cntCows = 1;
// Position of last placed cow
int last = nums[0];
for (int i = 1; i < n; i++) {
if (nums[i] - last >= dist) {
// Place next cow
cntCows++;
// Update the last location
last = nums[i];
}
if (cntCows >= cows) return true;
}
return false;
}
public:
/* Function to find the maximum possible minimum
distance 'k' cows can have between them in 'stalls' */
int aggressiveCows(vector<int> &nums, int k) {
// Size of array
int n = nums.size();
// Sort the nums
sort(nums.begin(), nums.end());
int limit = nums[n - 1] - nums[0];
for (int i = 1; i <= limit; i++) {
if (canWePlace(nums, i, k) == false) {
return (i - 1);
}
}
//Retrun the answer
return limit;
}
};
int main() {
vector<int> nums = {0, 3, 4, 7, 10, 9};
int k = 4;
// Create an instance of the Solution class
Solution sol;
int ans = sol.aggressiveCows(nums, k);
// Output the result
cout << "The maximum possible minimum distance is: " << ans << "\n";
return 0;
}
import java.util.Arrays;
class Solution {
/* Function to check if we can place 'cows' cows
with at least 'dist' distance apart */
private boolean canWePlace(int[] nums, int dist, int cows) {
// Size of array
int n = nums.length;
// Number of cows placed
int cntCows = 1;
// Position of last placed cow
int last = nums[0];
for (int i = 1; i < n; i++) {
if (nums[i] - last >= dist) {
// Place next cow
cntCows++;
// Update the last location
last = nums[i];
}
if (cntCows >= cows) return true;
}
return false;
}
/* Function to find the maximum possible minimum
distance 'k' cows can have between them in nums */
public int aggressiveCows(int[] nums, int k) {
// Size of array
int n = nums.length;
// Sort the nums
Arrays.sort(nums);
int limit = nums[n - 1] - nums[0];
for (int i = 1; i <= limit; i++) {
if (!canWePlace(nums, i, k)) {
return (i - 1);
}
}
// Return the answer
return limit;
}
public static void main(String[] args) {
int[] nums = {0, 3, 4, 7, 10, 9};
int k = 4;
// Create an instance of the Solution class
Solution sol = new Solution();
int ans = sol.aggressiveCows(nums, k);
// Output the result
System.out.println("The maximum possible minimum distance is: " + ans);
}
}
class Solution:
"""Function to check if we can place 'cows'
cows with at least 'dist' distance apart"""
def canWePlace(self, nums, dist, cows):
# Size of array
n = len(nums)
# Number of cows placed
cntCows = 1
# Position of last placed cow
last = nums[0]
for i in range(1, n):
if nums[i] - last >= dist:
# Place next cow
cntCows += 1
# Update the last location
last = nums[i]
if cntCows >= cows:
return True
return False
""" Function to find the maximum possible minimum
distance 'k' cows can have between them in 'nums'"""
def aggressiveCows(self, nums, k):
# Size of array
n = len(nums)
# Sort the nums
nums.sort()
limit = nums[-1] - nums[0]
for i in range(1, limit + 1):
if not self.canWePlace(nums, i, k):
return i - 1
# Return the answer
return limit
if __name__ == "__main__":
nums = [0, 3, 4, 7, 10, 9]
k = 4
# Create an instance of the Solution class
sol = Solution()
ans = sol.aggressiveCows(nums, k)
# Output the result
print("The maximum possible minimum distance is:", ans)
class Solution {
/* Function to check if we can place 'cows'
cows with at least 'dist' distance apart */
canWePlace(nums, dist, cows) {
// Size of array
let n = nums.length;
// Number of cows placed
let cntCows = 1;
// Position of last placed cow
let last = nums[0];
for (let i = 1; i < n; i++) {
if (nums[i] - last >= dist) {
// Place next cow
cntCows++;
// Update the last location
last = nums[i];
}
if (cntCows >= cows) return true;
}
return false;
}
/* Function to find the maximum possible minimum
distance 'k' cows can have between them in 'nums' */
aggressiveCows(nums, k) {
// Size of array
let n = nums.length;
// Sort the nums
nums.sort((a, b) => a - b);
let limit = nums[n - 1] - nums[0];
for (let i = 1; i <= limit; i++) {
if (!this.canWePlace(nums, i, k)) {
return i - 1;
}
}
// Return the answer
return limit;
}
}
function main() {
let nums = [0, 3, 4, 7, 10, 9];
let k = 4;
// Create an instance of the Solution class
let sol = new Solution();
let ans = sol.aggressiveCows(nums, k);
// Output the result
console.log("The maximum possible minimum distance is:", ans);
}
// Call the main function
main();
Here, the idea is to use binary search as the search range from [1 , max-min] is sorted. So, the brute-force solution can be optimized by dividing the space into two halves: one consisting of potential answers and the other of non-viable options.
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
/* Function to check if we can place 'cows' cows
with at least 'dist' distance apart in 'stalls' */
bool canWePlace(vector<int> &nums, int dist, int cows) {
// Size of array
int n = nums.size();
// Number of cows placed
int cntCows = 1;
// Position of last placed cow
int last = nums[0];
for (int i = 1; i < n; i++) {
if (nums[i] - last >= dist) {
// Place next cow
cntCows++;
// Update the last location
last = nums[i];
}
if (cntCows >= cows) return true;
}
return false;
}
public:
/* Function to find the maximum possible minimum
distance 'k' cows can have between them in 'stalls' */
int aggressiveCows(vector<int> &nums, int k) {
// Size of array
int n = nums.size();
// Sort the nums
sort(nums.begin(), nums.end());
int low = 1, high = nums[n - 1] - nums[0];
//Apply binary search:
while (low <= high) {
int mid = (low + high) / 2;
if (canWePlace(nums, mid, k) == true) {
low = mid + 1;
}
else high = mid - 1;
}
return high;
}
};
int main() {
vector<int> nums = {0, 3, 4, 7, 10, 9};
int k = 4;
// Create an instance of the Solution class
Solution sol;
int ans = sol.aggressiveCows(nums, k);
// Output the result
cout << "The maximum possible minimum distance is: " << ans << "\n";
return 0;
}
import java.util.Arrays;
class Solution {
/* Function to check if we can place 'cows' cows
with at least 'dist' distance apart */
private boolean canWePlace(int[] nums, int dist, int cows) {
// Size of array
int n = nums.length;
// Number of cows placed
int cntCows = 1;
// Position of last placed cow
int last = nums[0];
for (int i = 1; i < n; i++) {
if (nums[i] - last >= dist) {
// Place next cow
cntCows++;
// Update the last location
last = nums[i];
}
if (cntCows >= cows) return true;
}
return false;
}
/* Function to find the maximum possible minimum
distance 'k' cows can have between them in nums */
public int aggressiveCows(int[] nums, int k) {
// Size of array
int n = nums.length;
// Sort the nums
Arrays.sort(nums);
int low = 1, high = nums[n - 1] - nums[0];
//Apply binary search:
while (low <= high) {
int mid = (low + high) / 2;
if (canWePlace(nums, mid, k) == true) {
low = mid + 1;
}
else high = mid - 1;
}
return high;
}
public static void main(String[] args) {
int[] nums = {0, 3, 4, 7, 10, 9};
int k = 4;
// Create an instance of the Solution class
Solution sol = new Solution();
int ans = sol.aggressiveCows(nums, k);
// Output the result
System.out.println("The maximum possible minimum distance is: " + ans);
}
}
class Solution:
"""Function to check if we can place 'cows'
cows with at least 'dist' distance apart"""
def canWePlace(self, nums, dist, cows):
# Size of array
n = len(nums)
# Number of cows placed
cntCows = 1
# Position of last placed cow
last = nums[0]
for i in range(1, n):
if nums[i] - last >= dist:
# Place next cow
cntCows += 1
# Update the last location
last = nums[i]
if cntCows >= cows:
return True
return False
""" Function to find the maximum possible minimum
distance 'k' cows can have between them in 'nums'"""
def aggressiveCows(self, nums, k):
# Size of array
n = len(nums)
# Sort the nums
nums.sort()
low = 1
high = nums[n - 1] - nums[0]
# Apply binary search
while low <= high:
mid = (low + high) // 2
if self.canWePlace(nums, mid, k):
low = mid + 1
else:
high = mid - 1
return high
if __name__ == "__main__":
nums = [0, 3, 4, 7, 10, 9]
k = 4
# Create an instance of the Solution class
sol = Solution()
ans = sol.aggressiveCows(nums, k)
# Output the result
print("The maximum possible minimum distance is:", ans)
class Solution {
/* Function to check if we can place 'cows'
cows with at least 'dist' distance apart */
canWePlace(nums, dist, cows) {
// Size of array
let n = nums.length;
// Number of cows placed
let cntCows = 1;
// Position of last placed cow
let last = nums[0];
for (let i = 1; i < n; i++) {
if (nums[i] - last >= dist) {
// Place next cow
cntCows++;
// Update the last location
last = nums[i];
}
if (cntCows >= cows) return true;
}
return false;
}
/* Function to find the maximum possible minimum
distance 'k' cows can have between them in 'nums' */
aggressiveCows(nums, k) {
// Size of array
let n = nums.length;
// Sort the nums
nums.sort((a, b) => a - b);
let low = 1, high = nums[n - 1] - nums[0];
// Apply binary search
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (this.canWePlace(nums, mid, k)) {
low = mid + 1;
} else {
high = mid - 1;
}
}
//Return the answer
return high;
}
}
function main() {
let nums = [0, 3, 4, 7, 10, 9];
let k = 4;
// Create an instance of the Solution class
let sol = new Solution();
let ans = sol.aggressiveCows(nums, k);
// Output the result
console.log("The maximum possible minimum distance is:", ans);
}
// Call the main function
main();
Q: Why sort the stalls?
A: Sorting ensures the stalls are in sequential order, which is necessary to calculate the distance between adjacent stalls. Without sorting, the distance calculations would be incorrect, making placement infeasible.
Q: What is the feasibility function?
A: The feasibility function checks if it is possible to place k cows such that the minimum distance between any two cows is mid. This involves greedily placing cows in the stalls and counting how many can be placed.
Q: What if there are constraints on stall availability?
A: If some stalls are unavailable, exclude them from the sorted list. Adjust the feasibility function to skip unavailable stalls during placement.
Q: How would you handle dynamic updates to the stalls?
A: Use a data structure like a balanced binary search tree to maintain the sorted order of stall positions dynamically. Update the tree and re-evaluate the feasibility function as stalls are added or removed.