Minimum Speed to Arrive on Time - Problem

You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.

Each train can only depart at an integer hour, so you may need to wait in between each train ride.

For example: If the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.

Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.

Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.

Input & Output

Example 1 — Basic Case
$ Input: dist = [1,1,2], hour = 4.0
Output: 1
💡 Note: At speed 1: Train 1 takes ceil(1/1)=1 hour, Train 2 takes ceil(1/1)=1 hour, Train 3 takes 2/1=2 hours. Total: 1+1+2=4.0 hours ≤ 4.0
Example 2 — Need Higher Speed
$ Input: dist = [1,1,100000], hour = 2.01
Output: 10000000
💡 Note: Need very high speed for last train. At speed 10^7: ceil(1/10^7) + ceil(1/10^7) + 100000/10^7 = 1+1+0.01 = 2.01 hours
Example 3 — Impossible Case
$ Input: dist = [1,1,1], hour = 2.0
Output: -1
💡 Note: Need at least 2 integer hours for first 2 trains, plus time for last train. Minimum time is 2+ε > 2.0, so impossible

Constraints

  • n == dist.length
  • 1 ≤ n ≤ 105
  • 1 ≤ dist[i] ≤ 105
  • 1 ≤ hour ≤ 109
  • There will be at most two digits after the decimal point in hour.

Visualization

Tap to expand
Train Speed Problem: Find minimum speed to arrive on timeInputdist=[1,1,2], hour=4.0ProcessBinary search speedsOutputMinimum speed = 1Train 1dist=1Train 2dist=1Train 3dist=2At speed 1: ceil(1/1) + ceil(1/1) + 2/1 = 1+1+2 = 4.0 hours✓ Exactly meets the 4.0 hour deadline!Key: First n-1 trains must depart at integer hours
Understanding the Visualization
1
Input
Array of distances and time limit
2
Process
Calculate time for each speed, considering integer hour waits
3
Output
Minimum speed that allows on-time arrival
Key Takeaway
🎯 Key Insight: Binary search on answer works because the problem has monotonic property - if speed X works, any speed > X also works
Asked in
Google 12 Amazon 8 Microsoft 6 Facebook 5
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen