Easy Binary Search Solution


#1

int val(vector &A, int B,int m){
int s=0;
for(int i=0;i<A.size();i++){
if(A[i]>m)
s+=(A[i]-m);
if(s>B)return 1;
}
if(s==B)return 0;
return -1;
}
int Solution::solve(vector &A, int B) {
int res=-1;
int l=0;
int h=*max_element(A.begin(), A.end());
while(l<=h){
int mid=l+(h-l)/2;
if(val(A,B,mid)==0)
{res=mid;return mid;}
else if(val(A,B,mid)==-1)
h=mid-1;
else {l=mid+1; res=mid;}
}
return res;
}