Skip to content

Commit 2c65a33

Browse files
authored
Merge pull request #1194 from t3chkid/main
Add solution for 853. Car Fleet in Kotlin
2 parents 27b4d00 + 69a1a1d commit 2c65a33

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Diff for: kotlin/853-Car-Fleet.kt

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
fun carFleet(target: Int, position: IntArray, speed: IntArray): Int {
3+
val sortedPairs = position
4+
.zip(speed)
5+
.sortedBy { (position, _) -> position }
6+
var numberOfFleets = 1
7+
var timeRequiredForCarInFrontToReachInTarget =
8+
(target - sortedPairs[sortedPairs.lastIndex].first) / sortedPairs[sortedPairs.lastIndex].second.toFloat()
9+
var timeRequiredForCurrentCarToReachTarget: Float
10+
for (i in (sortedPairs.lastIndex - 1) downTo 0) {
11+
timeRequiredForCurrentCarToReachTarget = (target - sortedPairs[i].first) / sortedPairs[i].second.toFloat()
12+
if (timeRequiredForCurrentCarToReachTarget > timeRequiredForCarInFrontToReachInTarget) {
13+
// the current car requires more time to reach the destination
14+
// than the car in front of it.
15+
numberOfFleets++
16+
timeRequiredForCarInFrontToReachInTarget = timeRequiredForCurrentCarToReachTarget
17+
}
18+
}
19+
return numberOfFleets
20+
}
21+
}

0 commit comments

Comments
 (0)