Leetcode 1870: Minimum Speed to Arrive on Time

grid47
grid47
Exploring patterns and algorithms
May 4, 2024 6 min read

You are given a list of n train ride distances and a floating-point number hour which indicates the total time you have to reach your destination. You need to determine the minimum integer speed (in kilometers per hour) at which all the trains must travel to reach the office on time. If it is impossible, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array dist representing the distances for each train ride, and a floating-point number hour representing the total time to reach the office.
Example: [2, 5, 3], hour = 8
Constraints:
• 1 <= dist.length <= 10^5
• 1 <= dist[i] <= 10^5
• 1 <= hour <= 10^9
• hour has at most two decimal places.
Output: Return the minimum integer speed (in km/h) that all trains must travel to reach on time, or return -1 if it is impossible.
Example: 2
Constraints:
• The result should be an integer speed or -1.
Goal: The goal is to find the minimum integer speed that satisfies the given time constraint for all train rides.
Steps:
• Start with the smallest possible speed and calculate the time taken for each train ride.
• For each train ride, calculate the time based on the speed, and determine if you need to wait to depart at an integer hour.
• Use binary search to find the minimum speed that allows you to arrive at the office on time.
Goal: Constraints on the input values.
Steps:
• 1 <= dist.length <= 10^5
• 1 <= dist[i] <= 10^5
• 1 <= hour <= 10^9
• hour has at most two decimal places.
Assumptions:
• All the train distances are positive integers.
• The total time must be greater than or equal to the time required for each train ride.
Input: [2, 5, 3], hour = 8
Explanation: At speed 2, the time taken for each train ride ensures that you arrive exactly on time (8 hours).

Input: [1, 5, 3], hour = 3.4
Explanation: At speed 3, the total time is less than 3.4 hours, but it is impossible to make it on time as the total time is 3 hours.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus