Similar Problems

Similar Problems not available

The Latest Time To Catch A Bus - Leetcode Solution

Companies:

LeetCode:  The Latest Time To Catch A Bus Leetcode Solution

Difficulty: Medium

Topics: sorting two-pointers array binary-search  

The Latest Time To Catch A Bus problem on LeetCode is a binary search problem that requires finding the maximum time that a person can spend walking to catch a bus in a given city.

The problem statement is as follows:

You are given an array of integers dist where dist[i] represents the distance between the ith city and the next city. There is a bus station in the 0th city. A bus starts from the station and moves toward the last city by one unit of distance each time.

Given an integer hour, return the maximum distance that you can cover in hour hours by walking.

If you cannot reach the last city in hour hours, return -1.

To solve the problem, we need to perform a binary search on the range of possible values for the maximum distance that can be covered in hour hours. The range of values is between 1 and 10^9, as the distance between any two cities can be up to 10^5 and hour can also be up to 10^9.

We first define a function that returns whether it is possible to reach the last city in hour hours given the maximum distance d. This function takes the input array of distances and the maximum possible distance d as the input.

We then perform a binary search on the range [1, 10^9] to find the maximum possible distance that can be covered in hour hours. For each mid value in the range, we call the function that checks whether it is possible to reach the last city in hour hours given the maximum distance mid. If it is possible, we update the maximum distance that can be covered in hour hours and continue the search in the upper half of the range. If it is not possible, we continue the search in the lower half of the range.

The final answer is the maximum possible distance that can be covered in hour hours.

Here is the Python implementation of the solution:

class Solution:
    def is_possible(self, dist: List[int], d: int, hour: int) -> bool:
        time = 0
        n = len(dist)
        for i in range(n-1):
            time += (dist[i] + d - 1) // d
        time += dist[-1] / d
        return time <= hour
    
    def maxDistance(self, dist: List[int], hour: int) -> int:
        left = 1
        right = 10**9
        ans = -1
        while left <= right:
            mid = (left + right) // 2
            if self.is_possible(dist, mid, hour):
                ans = mid
                left = mid + 1
            else:
                right = mid - 1
        return ans

The time complexity of the solution is O(N log M), where N is the number of cities in the array and M is the maximum possible distance between any two cities (10^9 in this case). The space complexity is O(1), as we do not use any extra space.

The Latest Time To Catch A Bus Solution Code

1