import java.util.;
public class Main {
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
int s= cin.nextInt(), c = cin.nextInt(), arr[] = new int[s];
for(int i = 0;i<arr.length;i++){
arr[i] = cin.nextInt();
}
for(int count = 0;count<arr.length-2;count++){
for(int j = 0;j<arr.length-1-count;j++){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
int l = 0, h = arr[arr.length-1] - arr[0],ans =0;
while(l<=h){
int mid = (l+h)/2, req = midc, avail = arr[arr.length-1];
if(avail>req){
ans = mid;
l = mid +1;
}else if( avail<req){
h = mid -1;
}else if(avail == req){
ans = mid;
l = mid +1;
}
}
System.out.println(ans);
}
}=== what’s error in the code
Aggressive cows
you are not checking if the given mid point is valide for a solution .make a function to check if the mid point is valid.
public static boolean isValid(int[] a, int n ,int c, int ans) {
int pos=a[0];
int cow=1;
for(int i =1;i<n;i++) {
if(a[i]-pos>=ans) {
pos=a[i];
cow++;
if(cow==c) {
return true;
}
}
}
return false;
}
and everytime u check for m ,if it is valid make s=m+1 and update ans .else just do e=m-1