PROBLEM LINKS
DIFFICULTY
CAKEWALK
PREREQUISITES
Simple Math
PROBLEM
There are N cars on a narrow road that are moving in the same direction. Each car has maximum speed. No car can overtake other cars on this road. Each car will move at the maximum possible speed while avoiding any collisions. Count the number of cars which are moving at their maximum speeds.
QUICK EXPLANATION
Intuitively, a car is moving at its maximum speed if and only if all cars in front of it are moving at greater speeds (otherwise it will overtake the slower car). Therefore, the answer is the number of such cars.
EXPLANATION
Suppose that the cars are numbered 1 through N from front to back, and the maximum speed of the i-th car is maxSpeed[i]. From the intuitive observation above, we can directly come up with this naive solution:
answer = 0 for i = 1; i <= N; i++: allGreater = true for j = 1; j <= i-1; j++: if maxSpeed[j] < maxSpeed[i]: allGreater = false if allGreater: answer = answer + 1
Unfortunately, this solution runs in O(N^2) time, which will surely time out. We will need other observations.
Consider each car. From the problem statement, each car will:
- Avoid any collisions. Since the road is narrow, therefore, it will not move at greater speed than the car directly in front of it (if any).
- Move at the maximum possible speed. Therefore, it will move at speed of exactly min(the maximum speed of the car, the speed of the car directly in front of it).
From those observations, we can calculate the speed of each car in O(1) time. When calculating the speed of the i-th car, we have to know the speed of the (i-1)st car. Therefore, we must calculate the speeds in the right order (i.e., from the first car to the last car on the road). After that, we compare the speed of each car with its maximum speed.
A direct implementation of the above solution is as follows. This solution runs in O(N) time, which will pass the time limit.
answer = 0 speed[1] = maxSpeed[1] for i = 2; i <= N; i++: speed[i] = min(maxSpeed[i], speed[i-1]) for i = 1; i <= N; i++: if speed[i] == maxSpeed[i]: answer = answer + 1
Exercise
Try to solve this problem without creating the additional speed[]/maxSpeed[] array. Hint: we can always store only the speed of the last car we consider instead of storing all speeds in speed[] array.
SETTER’S SOLUTION
Can be found here
TESTER’S SOLUTION
Can be found here.