Minimum Speed to Arrive on Time
Find the slowest whole-number speed that gets you through a chain of trains within a time limit.
To reach the office you take nidist[i]hourhour
Example 1
Output: 1
Explanation: at speed 1, the rides take 1, 3 and 2 hours, so you arrive at exactly hour 6.
Example 2
Output: 3
Explanation: at speed 3, the first ride takes 1/3 hour, then you wait until hour 1. The second ride takes 1 hour, and the last takes 2/3 hour, so you arrive at about 2.67.
Example 3
Output: -1
Explanation: the first two trains take at least one whole hour each, so you cannot arrive before hour 2.
The Idea
You have probably waited on a platform for a train that leaves on the hour, even though you arrived early. That waiting is what makes this problem interesting. A faster train gets you to the next station sooner, but the next train still leaves at the same whole hour.
Take Example 2: three rides of 1, 3 and 2 kilometres, and 2.7 hours to do them. Look at the picture below. It shows the same trip at two speeds, with the limit hour = 2.7
In the row labelled speed 2, the 1 km ride takes half an hour, and then you wait until hour 1. The 3 km ride takes 1.5 hours and ends at 2.5, so you wait again, until hour 3. The 2 km ride ends at hour 4: late.
In the row labelled speed 3, the 1 km ride ends at about 0.33, and you wait until hour 1. The 3 km ride takes exactly one hour, so the last train leaves at hour 2 with no wait. Its 2 km take 2/3 of an hour, and you arrive at 2.67: on time.
Notice that the last ride has no wait after it. You get off and walk to the office, so its time counts as an exact fraction. Every other ride counts as a whole number of hours, its time rounded up.
So for any one speed, we can work out the arrival time. But which speed should we try? Speeds go up to 107, far too many to try one by one. Here is what helps: going faster never makes you arrive later. Each ride gets shorter or stays the same, and so does each wait. If speed 3 is on time, so are 4, 5 and every faster speed. If speed 2 is late, so is speed 1.
Ask "is this speed on time?" for the speeds 1, 2, 3, 4 and so on, and the answers read no, no, yes, yes, and stay yes. We want the first yes. Finding where answers switch from no to yes, by halving the range of candidates at each guess, is called binary search, and here it runs over the speeds instead of over an array.
Solution Approach
Turning that idea into code means settling four things: how to time the trip for one speed, how to search the speeds, when to give up with -1, and how to compare times with the limit exactly.
Timing the trip for one speed
How long does the trip take at speed sdist[i] / sdist[n - 1] / shour
Rounding up in whole numbers needs no fractions: (dist[i] + s - 1) / sdist[i] / s
Searching the speeds
The simple way is to try speed 1, then 2, then 3, until one is on time. Each try loops over all n trains, and the answer may be near 107, so that can mean ten million passes over the trains.
Binary search keeps a range from lohimidmidmidhimidmidlomid + 1
When no speed works
Why can a trip be impossible at any speed? However fast the trains go, each ride except the last ends with a wait until the next whole hour. Each of those first n - 1
Since the answer is promised to be at most 107, one check settles it: if even speed 107 is late, return -1 before the search starts.
Comparing times exactly
The arrival time is a fraction, and adding fractions as doublehourhour
wholeHours + last / speed <= limit / 100
Here wholeHourslastlimithour100 * speedlong
Java Solution
The method minSpeedOnTime
- First, set the search range:
is 1 andlo is 10,000,000. Storehi in hundredths ashour , withlimit .Math.round(hour * 100) - Ask the helper
whether speedonTime is on time. If it is not, return -1.hi - Then run a loop while
is less thanlo . Each round takes the speedhi halfway between them and asksmid about it. On time movesonTime down tohi , and late movesmid up tolo .mid + 1 - When the loop ends,
equalslo , and it is the slowest speed that is on time. Returnhi .lo
The helper onTimewholeHourswholeHourslimit100 * speed
The main
public class MinimumSpeedToArriveOnTime {
public static int minSpeedOnTime(int[] dist, double hour) {
int lo = 1;
int hi = 10000000; // the problem promises the answer is at most 10^7
long limit = Math.round(hour * 100); // hour in hundredths: it has at most two decimals
if (!onTime(dist, hi, limit)) {
return -1; // not even the fastest allowed speed is enough
}
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (onTime(dist, mid, limit)) {
hi = mid; // mid is fast enough: the answer is mid or slower
} else {
lo = mid + 1; // mid is too slow: the answer is faster
}
}
return lo;
}
// Every train except the last leaves on a whole hour, so round those rides up.
// Checks wholeHours + last / speed <= limit / 100, multiplied out by 100 * speed.
private static boolean onTime(int[] dist, int speed, long limit) {
long wholeHours = 0;
for (int i = 0; i < dist.length - 1; i++) {
wholeHours += (dist[i] + speed - 1) / speed; // dist[i] / speed, rounded up
}
return 100 * (wholeHours * speed + dist[dist.length - 1]) <= limit * speed;
}
public static void main(String[] args) {
System.out.println(minSpeedOnTime(new int[] {1, 3, 2}, 6));
System.out.println(minSpeedOnTime(new int[] {1, 3, 2}, 2.7));
System.out.println(minSpeedOnTime(new int[] {1, 3, 2}, 1.9));
System.out.println(minSpeedOnTime(new int[] {7}, 0.5));
System.out.println(minSpeedOnTime(new int[] {1, 1, 100000}, 2.01));
System.out.println(minSpeedOnTime(new int[] {11, 78368}, 1.64));
}
}
Running it prints:
1
3
-1
14
10000000
122450
The first three lines give 1, 3 and -1, the answers of the three examples. The fourth line, 14, comes from one train of 7 km with half an hour. With only one train there is no wait at all, and 7 km in half an hour needs exactly 14 km per hour.
The fifth line, 10000000, is the trip [1, 1, 100000]
Look at the last line, 122450, for [11, 78368]doubledoublehouronTime
Complexity
The work is one call to onTime
- Time: O(n log 107), where n is the number of trains. Halving the range of 107 speeds takes about 24 guesses, and each
call loops over all n distances once.onTime - Space: O(1).
adds into oneonTime , and the search keeps onlylong ,lo andhi , however many trains there are.mid
The same search for the smallest speed that is fast enough appears in