853. Car Fleet
There are n cars at given miles away from the starting mile 0, traveling to reach the mile target
ArrayExample 1:
- Input:
target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] - Output:
3 - Explanation: • The cars starting at
10 (speed 2) and8 (speed 4) become a fleet, meeting each other at12. The fleet forms attarget. • The car starting at0 (speed 1) does not catch up to any other car, so it is a fleet by itself. • The cars starting at5 (speed 1) and3 (speed 3) become a fleet, meeting each other at6. The fleet moves atspeed 1until it reachestarget.
Example 2:
- Input:
target = 10, position = [3], speed = [3] - Output:
1 - Explanation: There is only one car, hence there is only one fleet.
Example 3:
- Input:
target = 100, position = [0,2,4], speed = [4,2,1] - Output:
1 - Explanation: • The cars starting at
0 (speed 4) and2 (speed 2) become a fleet, meeting each other at4. The car starting at4 (speed 1) travels to5. • Then, the fleet at4 (speed 2) and the car atposition 5 (speed 1) become one fleet, meeting each other at6. The fleet moves atspeed 1until it reachestarget.
Constraints:
n == position.length == speed.length1 <= n <= 10^50 < target <= 10^60 <= position[i] < target- All the values of
positionare unique. 0 < speed[i] <= 10^6
Approach
Solution
class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
stack = []
for pos, spd in sorted(zip(position, speed), reverse=True):
time = (target - pos) / spd
if not stack or time > stack[-1]:
stack.append(time)
return len(stack)