Imagine you're planning your daily commute to work, and you must catch exactly n trains in sequence to reach your office. Each train travels a specific distance, but here's the catch: all trains can only depart at integer hours (1:00, 2:00, 3:00, etc.).
You're given:
- A floating-point number
hourrepresenting your total time budget to reach the office - An integer array
distwheredist[i]is the distance (in km) of theith train ride
Key Constraint: If a train ride finishes at a non-integer time (like 1.3 hours), you must wait until the next integer hour to board the next train. However, the last train can arrive at any time within your budget.
Goal: Find the minimum positive integer speed (km/h) that allows all trains to travel fast enough for you to reach the office within the given time limit. Return -1 if it's impossible.
Example: If you have trains with distances [1, 3, 2] and hour = 6.0, at speed 1 km/h: Train 1 takes 1 hour (depart at 0:00, arrive at 1:00), Train 2 takes 3 hours (depart at 1:00, arrive at 4:00), Train 3 takes 2 hours (depart at 4:00, arrive at 6:00). Total time = 6 hours โ
Input & Output
Visualization
Time & Space Complexity
Where S is the maximum possible speed (10^7) and n is number of trains. We might check up to 10^7 speeds, and for each speed we calculate time for n trains.
Only using a few variables to track current speed and time calculations
Constraints
- n == dist.length
- 1 โค n โค 105
- 1 โค dist[i] โค 105
- 1 โค hour โค 109
- hour will have at most two digits after the decimal point
- The answer is guaranteed to not exceed 107