Easy C++ solution logn


#1

bool isvalid(vector A,int mid,int B)
{
int sum=0;
for(int i=0;i<A.size();i++)
{
if(A[i]>mid)
sum=sum+(A[i]-mid);
if(sum>=B)
return true;
}
return false;
}
int Solution::solve(vector &A, int B) {
int ans=0;
int low=INT_MAX;
int high=-1;
for(int i=0;i<A.size();i++)
{
high=max(high,A[i]);
low=min(low,A[i]);
}
while(low<=high)
{
int mid=(low+high)/2;
if(isvalid(A,mid,B))
{
ans=mid;
low=mid+1;
}
else
{
high=mid-1;
}
}
return ans;
}


#2

This isn’t O(log(n)) , You are finding max,min that itself is O(n), then further more in binary seacrh you are callimg isvalid it’s O(n) which makes it O(nlogn).