I wrote the binary search code below:
class Solution {
public:
bool check(vector<int>& dist, double hour, int mid) {
if(mid==0) return false;
double sum=0.0;
for(int i=0; i<dist.size()-1; i++)
sum+=ceil((double)dist[i]/mid);
sum+=(double)dist.back()/mid;
return sum<=hour ? true : false;
// sum+=0.001f;
// return sum<hour || std::fabs(hour-sum)<=0.001f ? true : false;
}
int minSpeedOnTime(vector<int>& dist, double hour) {
int l=0, r=10000001;
while(l<r) {
int mid=l+(r-l)/2;
if(check(dist, hour, mid)) {
r=mid;
} else l=mid+1;
}
return r==10000001 ? -1 : r;
}
};
It works and gets "accepted", but I had few questions:
a. Is the statement return sum<=hour ? true : false;
correct? I am unsure because both sum
and hour
are double
s. Shouldn't we be using some 'epsilon' for '==' comparison, like discussed here?
b. If uncommented, the following statement:
return sum<hour || std::fabs(hour-sum)<=0.001f ? true : false;
yields an incorrect answer. Why? The problem statement says that "hour will have at most two digits after decimal". So why does it give a wrong answer?
c. It gets accepted, if I add 0.001f
:
sum+=0.001f;
return sum<hour || std::fabs(hour-sum)<=0.001f ? true : false;
Again, why?
Edit: Even std::fabs(hour-sum)==0.001f
above doesn't get accepted.
Edit2: The problem statement is here, but I am not asking about the solution, etc., so I have not posted it in the question.