Minimum Speed to Arrive on Time

Problem Description

So, you think you can just hop in your car and zoom off to your destination without a care in the world? Well, think again! The “Minimum Speed to Arrive on Time” problem is here to remind you that time waits for no one, especially not for those who can’t calculate their speed properly.

Imagine you’re late for a meeting, and your boss is already giving you the side-eye. You have a series of distances to cover, and you need to figure out the minimum speed you must maintain to arrive on time. Spoiler alert: if you think you can just drive like a tortoise and still make it, you might want to reconsider your life choices!

Code Solution


class Solution:
    def minSpeedOnTime(self, dist: list[int], hour: float) -> int:
        ans = -1
        l = 1
        r = int(1e7)

        def time(speed: int) -> float:
            summ = 0
            for i in range(len(dist) - 1):
                summ += math.ceil(dist[i] / speed)
            return summ + dist[-1] / speed

        while l <= r:
            m = (l + r) // 2
            if time(m) > hour:
                l = m + 1
            else:
                ans = m
                r = m - 1

        return ans

Approach Explanation

The code uses a binary search approach to find the minimum speed required to reach the destination on time. It defines a helper function time(speed) that calculates the total time taken to cover the distances at a given speed. The binary search iterates over possible speeds, adjusting the search range based on whether the calculated time exceeds the given hour.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n log(max_speed))
Space Complexity O(1)

Real-World Example

Picture this: You’re on a road trip with friends, and you promised to reach the beach by noon. You have a series of pit stops (distances) along the way. If you don’t calculate your speed correctly, you might end up stuck in traffic, missing out on that glorious sunbathing session. The “Minimum Speed to Arrive on Time” problem is just like that—it’s all about making sure you hit the road with the right speed to avoid being the last one to the party!

Similar Problems

If you enjoyed this problem, you might also like these: