Maps app~25 min2s · 256 MBtarget O(n log (100 × L)) time, O(1) spaceclassic twin: lc-1870binary-search-answer
A rail app plans a journey made of several legs, one train after another. Every train runs at the same speed, in kilometres an hour. A train can leave only at the start of a whole hour, so after each leg except the last the traveller waits for the next whole hour.
The last leg needs no waiting, because the journey ends on arrival. The traveller has a time limit for the whole journey. The app wants the smallest whole speed that makes the journey in time.
Write min_speed(legs, limit).
legs[i] is the length of the i-th leg in whole kilometres.d kilometres at speed v takes d / v hours. After every leg except the last, round the time up to a whole number of hours.v for which the total time is at most the limit, or -1 when no speed is enough.Input: legs = [5, 8, 3, 6], limit = 450
Output: 8At speed 8, the first three legs take 1, 1 and 1 hours after rounding up, which is 3 hours. The last leg takes 6 / 8 = 0.75 hours, so the total is 3.75 hours. At speed 7 the leg of 8 km takes 2 hours, and the total is 4.86 hours, which is over the limit of 4.50. The solution searches the speeds from 1 to 800, where 800 is 100 times the longest leg.
| lo | hi | Speed tested | On time? | Decision |
|---|---|---|---|---|
| 1 | 800 | 400 | yes | hi becomes 400 |
| 1 | 400 | 200 | yes | hi becomes 200 |
| 1 | 200 | 100 | yes | hi becomes 100 |
| 1 | 100 | 50 | yes | hi becomes 50 |
| 1 | 50 | 25 | yes | hi becomes 25 |
| 1 | 25 | 13 | yes | hi becomes 13 |
| 1 | 13 | 7 | no | lo becomes 8 |
| 8 | 13 | 10 | yes | hi becomes 10 |
| 8 | 10 | 9 | yes | hi becomes 9 |
| 8 | 9 | 8 | yes | hi becomes 8 |
Input: legs = [1, 3, 2], limit = 190
Output: -1The first two legs take at least 1 hour each, and the last leg takes a positive time, so the journey takes more than 2 hours.
Input: legs = [4], limit = 150
Output: 3At speed 3, the single leg takes 4 / 3 = 1.33 hours, which fits in 1.50 hours. At speed 2 it takes 2 hours.
1 ≤ legs.length ≤ 100,0001 ≤ legs[i] ≤ 100,000 (kilometres)1 ≤ limit ≤ 100,000,000,000 (hundredths of an hour)The speed can be up to 100 × 100,000 = 10^7. Trying every speed from 1 upwards, with a pass over the legs for each, costs up to 10^7 × 10^5 = 10^12 steps. A higher speed never takes longer, so halving the range needs about 24 passes, which is about 2.4 million steps.