-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0853-car-fleet.kt
21 lines (21 loc) · 1.04 KB
/
0853-car-fleet.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
fun carFleet(target: Int, position: IntArray, speed: IntArray): Int {
val sortedPairs = position
.zip(speed)
.sortedBy { (position, _) -> position }
var numberOfFleets = 1
var timeRequiredForCarInFrontToReachInTarget =
(target - sortedPairs[sortedPairs.lastIndex].first) / sortedPairs[sortedPairs.lastIndex].second.toFloat()
var timeRequiredForCurrentCarToReachTarget: Float
for (i in (sortedPairs.lastIndex - 1) downTo 0) {
timeRequiredForCurrentCarToReachTarget = (target - sortedPairs[i].first) / sortedPairs[i].second.toFloat()
if (timeRequiredForCurrentCarToReachTarget > timeRequiredForCarInFrontToReachInTarget) {
// the current car requires more time to reach the destination
// than the car in front of it.
numberOfFleets++
timeRequiredForCarInFrontToReachInTarget = timeRequiredForCurrentCarToReachTarget
}
}
return numberOfFleets
}
}