![]() |
In the aggressive cow’s problem, we are given an array of size n, where elements of the array denote the position of stalls. We are given k number of cows that we have to place in these stalls such that the minimum distance between any of two cows is maximum. It is a standard problem that can be solved optimally by using a binary search algorithm. Below are the approaches to solving the Aggressive cow’s problem: Table of Content Brute force ApproachWe will first sort the stall array. Now we will use a for loop to check all possible distances. Inside the loop create a “canweplace()” function to checks if it’s possible to place all cows with a certain minimum distance between them. Now, Iterate through all possible pairs of stalls and check if it’s possible to place cows with the distance between those stalls. Return the maximum minimum distance obtained. Example: To demonstrate aggressive cows problem using Naive Approach.
Output The maximum possible minimum distance using binary search algo is 3 Time Complexity: O(NlogN) + O(N*max(stalls[]) – min(stalls[]))) Space Complexity: O(1) Binary Search ApproachWe will use binary search algorithm to optimize the code and reduce time complexity of problem by reducing search space by half. First sort the stalls array. Take two pointers low and high such that low = 1 and high = stalls[n-1] – stalls[0]. Now perform binary search. Calculate the mid. Call “canWePlace()” function and Update the maximum possible minimum distance and search on right half , if not possible search on left half. Return the maximum minimum distance. Example: To demonstrate aggressive cows problem using binary search algorithm.
Output The maximum possible minimum distance using binary search algo is 3
Space Complexity: O(1) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |