Minimize max distance of Gas Station
Bugs/Correctness


In the binary search, when a good value (that is when valid returns true) is found, your code doesn't save it before trying to optimize it further.

if valid(distances, mid, k):
    h = mid - 0.1 # Now the best value is lost.


The best way is to save the best distance you found so far.

if valid(distances, mid, k):
    best_so_far = mid
    h = mid - 0.1
...
return best_so_far

(v - distances[i-1]) / mid, now if the distance between the stations is 6 and mid is 3, the result will be 2, while you really only need to add 1 gas station. What you really wanna do is to get the ceiling of distance / mid which will give you the number of pieces of length mid, then subtract one to get the number of gas stations in the middle. So math.ceil(distance / mid) - 1.


Code Style

Overall I think the code is really clean, with clear variable names and good modularity.


The part that gets the max distance between every 2 elements

max_distance = 0
for i, v in enumerate(distances):
  if i &gt; 0:
    max_distance = max(max_distance, v - distances[i-1])


Could be written in a more pythonic way as:

max_distance = max(a + b for a, b in zip(distances, distances[1:]))

The method name valid is not really readable, also the variable names mid and k are not expressive. So I would rename it to something like.

is_solvable(distances, distance_required, additional_stations)