Assign stalls to K cows to maximize the minimum distance between them
Last Updated :
20 Feb, 2023
Given a sorted array arr[] consisting of N integers which denote the position of a stall. You are also given an integer K which denotes the number of aggressive cows. You are given the task of assigning stalls to K cows such that the minimum distance between any two of them is the maximum possible.
Examples:
Input: N = 5, K = 3, arr[] = {1, 2, 4, 8, 9}
Output: 3
Explanation: We can place cow 1 at position 1, cow 2 at position 4 and cow 3 at position 9. So, the maximum possible minimum distance between two cows is 3.
Input: N = 6, K = 4, arr[] = {6, 7, 9, 11, 13, 15}
Output: 2
Explanation: We can place cow 1 at position 6, cow 2 at position 9 and cow 4 at position 15. So, the maximum possible minimum distance between two cows is 2.
Naive Approach: The basic way to solve the problem is as follows:
The maximum distance possible between two cows can be the difference between the maximum and minimum element (Which is less than the maximum element of the array) of the array and the minimum possible distance can be 1.
Follow the steps to solve the problem:
- We will start iterating from 1 to the maximum element of the array and for each distance,
- We will check whether it is possible to place all the cows in the barn by maintaining this minimum distance.
- If it is possible then we will store it as a possible answer and continue to search for a better answer.
- Else, break the loop, and return the answer.
Illustration:
Consider: N = 5, K = 3, arr = {1, 2, 4, 8, 9}.
- Maximum element = 9. So we will iterate between 1 to 9.
- At i = 1, we can place the cows at positions 1, 2, 4 maintaining the minimum distance of 1.
- At i = 2, we can place the cows at positions 1, 4, 8 maintaining the minimum distance of 2.
- At i = 3, we can place the cows at 1, 4, and 8 maintaining the minimum distance of 3.
- At i = 4, we can not place the cows by maintaining the minimum distance of 4.
- So, the largest possible distance is 3.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
bool ok(vector< int >& v, int x, int c)
{
int n = v.size();
int count = 1;
int d = v[0];
for ( int i = 1; i < n; i++) {
if (v[i] - d >= x) {
d = v[i];
count++;
}
else {
continue ;
}
}
if (count >= c) {
return true ;
}
return false ;
}
int aggressive_cows(vector< int >& v, int n, int k)
{
long long ans = -1;
int maxi = 0;
for ( int i = 0; i < n; i++) {
maxi = max(maxi, v[i]);
}
for ( long long i = 1; i <= maxi; i++) {
if (ok(v, i, k)) {
ans = i;
}
else {
break ;
}
}
return ans;
}
int main()
{
int K = 3;
vector< int > arr = { 1, 2, 4, 8, 9 };
int N = arr.size();
int ans = aggressive_cows(arr, N, K);
cout << ans << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
int K = 3 ;
int [] arr = { 1 , 2 , 4 , 8 , 9 };
int N = arr.length;
System.out.println(aggressive_cows(arr, N, K));
}
public static boolean ok( int [] v, int x, int c)
{
int n = v.length;
int count = 1 ;
int d = v[ 0 ];
for ( int i = 1 ; i < n; i++) {
if (v[i] - d >= x) {
d = v[i];
count++;
}
else {
continue ;
}
}
if (count >= c) {
return true ;
}
return false ;
}
public static int aggressive_cows( int [] v, int n, int k)
{
long ans = - 1 ;
int maxi = 0 ;
for ( int i = 0 ; i < n; i++) {
maxi = Math.max(maxi, v[i]);
}
for ( long i = 1 ; i <= maxi; i++) {
if (ok(v, ( int )i, k)) {
ans = i;
}
else
break ;
}
return ( int )ans;
}
}
|
Python3
def ok(v,x,c):
n = len (v)
count = 1
d = v[ 0 ]
for i in range ( 1 ,n):
if (v[i] - d> = x):
d = v[i]
count = count + 1
else :
continue
if (count> = c):
return True
return False
def aggressive_cows(v,n,k):
ans = - 1
maxi = 0
for i in range (n):
maxi = max (maxi,v[i])
for i in range ( 1 ,maxi + 1 ):
if (ok(v,i,k)):
ans = i
else :
break
return ans
K = 3
arr = [ 1 , 2 , 4 , 8 , 9 ]
N = len (arr)
ans = aggressive_cows(arr,N,K)
print (ans)
|
C#
using System;
class Program {
static void Main( string [] args)
{
int K = 3;
int [] arr = { 1, 2, 4, 8, 9 };
int N = arr.Length;
Console.WriteLine(aggressive_cows(arr, N, K));
}
public static bool ok( int [] v, int x, int c)
{
int n = v.Length;
int count = 1;
int d = v[0];
for ( int i = 1; i < n; i++)
if (v[i] - d >= x) {
d = v[i];
count++;
}
else
continue ;
if (count >= c)
return true ;
return false ;
}
public static int aggressive_cows( int [] v, int n, int k)
{
long ans = -1;
int maxi = 0;
for ( int i = 0; i < n; i++)
maxi = Math.Max(maxi, v[i]);
for ( long i = 1; i <= maxi; i++)
if (ok(v, ( int )i, k))
ans = i;
else
break ;
return ( int )ans;
}
}
|
Javascript
function ok(v, x, c) {
let n = v.length;
let count = 1;
let d = v[0];
for (let i = 1; i < n; i++) {
if (v[i] - d >= x) {
d = v[i];
count++;
}
else {
continue ;
}
}
if (count >= c) {
return true ;
}
return false ;
}
function aggressive_cows(v, n, k) {
let ans = -1;
let maxi = 0;
for (let i = 0; i < n; i++) {
maxi = Math.max(maxi, v[i]);
}
for (let i = 1; i <= maxi; i++) {
if (ok(v, i, k)) {
ans = i;
}
else {
break ;
}
}
return ans;
}
let K = 3;
let arr = [1, 2, 4, 8, 9];
let N = arr.length;
let ans = aggressive_cows(arr, N, K);
console.log(ans);
|
Time Complexity: O(N*(max element in the input array))
Auxiliary Space: O(1).
Efficient Approach: In the above approach, the search for the answer can be optimized using Binary search.
As we have seen in the case of brute force solution we are iterating from 1 to the maximum element of the array and at each distance, we check whether it can be our possible answer or not. Instead of doing this, we can run a binary search from 1 to the maximum element of the array.
Follow the steps to solve the problem:
- Apply a binary search between 1 and the maximum element of the array.
- Each time find the middle element of the search space.
- If that middle element can be a possible minimum distance store it as a possibility until we find a better answer, then move in the right direction in the search space.
- Else, we will move left in our search space.
- When the binary search is complete, return the answer.
Illustration:
Consider: N = 5, K =3, arr = {1, 2, 4, 8, 9}.
- Maximum element = 9. So our search space will be 1 to 9.
- First, L = 1 and R = 9, mid = 5; we can not place the cows by maintaining the minimum distance of 5. So, we will move left in our search space.
- Now, L = 1 and R = 4, mid = 2; we can place the cows at positions 1, 4, and 8 maintaining the minimum distance of 2. So, we will store 2 as a possible answers and move right into our search space.
- Now, L=3 and R=4, mid = 3; we can place the cows at positions 1, 4, and 8 maintaining the minimum distance of 3. So, we will store 3 as a possible answers and move right into our search space.
- Now, L = 4 and R = 4, mid = 4; we can not place the cows by maintaining the minimum distance of 5. So, we will move left in our search space.
- Now, L = 4 and R = 3, Since, L > R, our binary search is complete, and the largest possible answer is 3.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
bool ok(vector< int >& v, int x, int c)
{
int n = v.size();
int count = 1;
int d = v[0];
for ( int i = 1; i < n; i++) {
if (v[i] - d >= x) {
d = v[i];
count++;
}
else {
continue ;
}
}
if (count >= c) {
return true ;
}
return false ;
}
int aggressive_cows(vector< int >& v, int n, int k)
{
int l = 1;
int r = 1e9;
int ans = -1;
while (r >= l) {
int mid = l + (r - l) / 2;
if (ok(v, mid, k)) {
ans = mid;
l = mid + 1;
}
else {
r = mid - 1;
}
}
return ans;
}
int main()
{
int K = 3;
vector< int > arr = { 1, 2, 8, 4, 9 };
int N = arr.size();
int ans = aggressive_cows(arr, N, K);
cout << ans << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static boolean ok( int [] v, int x, int c)
{
int n = v.length;
int count = 1 ;
int d = v[ 0 ];
for ( int i = 1 ; i < n; i++) {
if (v[i] - d >= x) {
d = v[i];
count++;
}
else {
continue ;
}
}
if (count >= c) {
return true ;
}
return false ;
}
static int aggressive_cows( int [] v, int n, int k)
{
int l = 1 ;
int r = 1000000000 ;
int ans = - 1 ;
while (r >= l) {
int mid = l + (r - l) / 2 ;
if (ok(v, mid, k)) {
ans = mid;
l = mid + 1 ;
}
else {
r = mid - 1 ;
}
}
return ans;
}
public static void main(String[] args)
{
int K = 3 ;
int [] arr = new int [] { 1 , 2 , 8 , 4 , 9 };
int N = arr.length;
System.out.println(aggressive_cows(arr, N, K));
}
}
|
Python3
def ok(v, x, c):
n = len (v)
count = 1
d = v[ 0 ]
for i in range ( 1 , n):
if (v[i] - d > = x):
d = v[i]
count + = 1
else :
continue
if (count > = c):
return True
return False
def aggressive_cows(v, n, k):
l = 1
r = 1000000000
ans = - 1
while (r > = l):
mid = l + (r - l) / / 2
if (ok(v, mid, k)):
ans = mid
l = mid + 1
else :
r = mid - 1
return ans
if __name__ = = '__main__' :
K = 3
arr = [ 1 , 2 , 8 , 4 , 9 ]
N = len (arr)
print (aggressive_cows(arr, N, K))
|
C#
using System;
class Program {
static bool ok( int [] v, int x, int c)
{
int n = v.Length;
int count = 1;
int d = v[0];
for ( int i = 1; i < n; i++) {
if (v[i] - d >= x) {
d = v[i];
count++;
}
else
continue ;
}
if (count >= c)
return true ;
return false ;
}
static int aggressive_cows( int [] v, int n, int k)
{
int l = 1;
int r = 1000000000;
int ans = -1;
while (r >= l) {
int mid = l + (r - l) / 2;
if (ok(v, mid, k)) {
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
return ans;
}
public static void Main()
{
int K = 3;
int [] arr = new int [] { 1, 2, 8, 4, 9 };
int N = arr.Length;
Console.WriteLine(aggressive_cows(arr, N, K));
}
}
|
Javascript
function ok(v, x, c) {
var n = v.length;
var count = 1;
var d = v[0];
for ( var i = 1; i < n; i++) {
if (v[i] - d >= x) {
d = v[i];
count++;
} else {
continue ;
}
}
if (count >= c) {
return true ;
}
return false ;
}
function aggressive_cows(v, n, k) {
var l = 1;
var r = 1e9;
var ans = -1;
while (r >= l) {
var mid = (l + (r - l) / 2) | 0;
if (ok(v, mid, k)) {
ans = mid;
l = mid + 1;
}
else {
r = mid - 1;
}
}
return ans;
}
var K = 3;
var arr = [1, 2, 8, 4, 9];
var N = arr.length;
var ans = aggressive_cows(arr, N, K);
console.log(ans);
|
Time Complexity: O(N * log(maximum element of the array ))
Auxiliary Space: O(1)
More Efficient Approach:
As we have seen in the case of brute force solution we are iterating from 0 to the maximum element of the array and at each distance, we check whether it can be our possible answer or not.
In Efficient Process we can run a binary search from 0 to the maximum element in the array.
But more than all we can run binary search from 0 to Maximum difference of the array.
In sorted array is A[N-1] – A[0] (last – first element in the array) is the maximum difference possible. It works perfectly fine, as our search space is that only, we can never get a difference that is greater than this.
This saves a lot of iterations in many cases, one such example is
- Arr = [70, 70, 70, 70] N=4, K=3
- Here Efficient method runs binary search from 0 to 70.
- More Efficient method (this method) runs binary search from 0 to 0. (A[N-1] – A[0] = 0)
C++
#include <bits/stdc++.h>
using namespace std;
bool ok(vector< int >& v, int x, int c)
{
int n = v.size();
int count = 1;
int last = 0;
for ( int i = 0; i < n; i++) {
if (v[i] - v[last] >= x) {
last = i;
count++;
}
if (count >= c) {
return true ;
}
}
return false ;
}
int aggressive_cows(vector< int >& v, int n, int k)
{
int l = 0;
int r = v[n-1] - v[0];
int ans = -1;
while (l<=r) {
int mid = l + (r - l) / 2;
if (ok(v, mid, k)) {
ans = mid;
l = mid + 1;
}
else {
r = mid - 1;
}
}
return ans;
}
int main()
{
int K = 3;
vector< int > arr = { 1, 2, 4, 8, 9 };
int N = arr.size();
int ans = aggressive_cows(arr, N, K);
cout << ans << endl;
return 0;
}
|
Java
import java.util.Vector;
class GFG {
static boolean ok(Vector<Integer> v, int x, int c) {
int n = v.size();
int count = 1 ;
int last = 0 ;
for ( int i = 0 ; i < n; i++) {
if (v.get(i) - v.get(last) >= x) {
last = i;
count++;
}
if (count >= c) {
return true ;
}
}
return false ;
}
static int aggressive_cows(Vector<Integer> v, int n, int k) {
int l = 0 ;
int r = v.get(n- 1 ) - v.get( 0 );
int ans = - 1 ;
while (l <= r) {
int mid = l + (r - l) / 2 ;
if (ok(v, mid, k)) {
ans = mid;
l = mid + 1 ;
} else {
r = mid - 1 ;
}
}
return ans;
}
public static void main(String[] args) {
int K = 3 ;
Vector<Integer> arr = new Vector<Integer>();
arr.add( 1 );
arr.add( 2 );
arr.add( 4 );
arr.add( 8 );
arr.add( 9 );
int N = arr.size();
int ans = aggressive_cows(arr, N, K);
System.out.println(ans);
}
}
|
Python3
import math
def ok(v, x, c):
n = len (v);
count = 1 ;
last = 0 ;
for i in range ( 0 ,n):
if (v[i] - v[last] > = x) :
last = i;
count + = 1 ;
if (count > = c) :
return True ;
return False ;
def aggressive_cows(v, n, k):
l = 0 ;
r = v[n - 1 ] - v[ 0 ];
ans = - 1 ;
while (l< = r):
mid = l + math.floor((r - l) / 2 );
if (ok(v, mid, k)):
ans = mid;
l = mid + 1 ;
else :
r = mid - 1 ;
return ans;
K = 3 ;
arr = [ 1 , 2 , 4 , 8 , 9 ];
N = len (arr);
ans = aggressive_cows(arr, N, K);
print (ans);
|
Javascript
function ok(v, x, c)
{
let n = v.length;
let count = 1;
let last = 0;
for (let i = 0; i < n; i++) {
if (v[i] - v[last] >= x) {
last = i;
count++;
}
if (count >= c) {
return true ;
}
}
return false ;
}
function aggressive_cows(v, n, k)
{
let l = 0;
let r = v[n-1] - v[0];
let ans = -1;
while (l<=r) {
let mid = l + Math.floor((r - l) / 2);
if (ok(v, mid, k)) {
ans = mid;
l = mid + 1;
}
else {
r = mid - 1;
}
}
return ans;
}
let K = 3;
let arr = [ 1, 2, 4, 8, 9 ];
let N = arr.length;
let ans = aggressive_cows(arr, N, K);
console.log(ans);
|
C#
using System;
using System.Collections.Generic;
class GFG {
static bool ok(List< int > v, int x, int c)
{
int n = v.Count;
int count = 1;
int last = 0;
for ( int i = 0; i < n; i++) {
if (v[i] - v[last] >= x) {
last = i;
count++;
}
if (count >= c) {
return true ;
}
}
return false ;
}
static int aggressive_cows(List< int > v, int n, int k)
{
int l = 0;
int r = v[n-1] - v[0];
int ans = -1;
while (l<=r) {
int mid = l + (r - l) / 2;
if (ok(v, mid, k)) {
ans = mid;
l = mid + 1;
}
else {
r = mid - 1;
}
}
return ans;
}
static public void Main()
{
int K = 3;
List< int > arr = new List< int >{ 1, 2, 4, 8, 9 };
int N = arr.Count;
int ans = aggressive_cows(arr, N, K);
Console.Write(ans);
}
}
|
Time Complexity: O(N * log(M))
- N = Size of the array.
- M = A[N-1] – A[0] (last – first element) Maximum possible difference in the array.
Auxiliary Space: O(1)
The above More Efficient Method Idea, Algorithm, and Code are contributed by Balakrishnan R (rbkraj000 – GFG ID).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...