Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1194 from t3chkid/main
Browse files Browse the repository at this point in the history
Add solution for 853. Car Fleet in Kotlin
  • Loading branch information
dissesmac authored Sep 29, 2022
2 parents 27b4d00 + 69a1a1d commit 2c65a33
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions kotlin/853-Car-Fleet.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,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
}
}

0 comments on commit 2c65a33

Please sign in to comment.