LeetCode/kt/maximum-units-on-a-truck.kt

24 lines
679 B
Kotlin
Raw Normal View History

2022-07-14 15:28:35 +02:00
class Solution {
data class BoxType(val boxes: Int, val units: Int)
2022-07-14 15:28:35 +02:00
fun toBoxType(x: IntArray): BoxType = BoxType(x[0], x[1])
fun maximumUnits(
boxTypes: Array<IntArray>,
truckSize: Int,
): Int =
2022-07-14 15:28:35 +02:00
boxTypes
.map { toBoxType(it) }
.sortedByDescending(BoxType::units)
.fold(0 to 0) { acc, boxType ->
if (acc.first < truckSize) {
val count = minOf(truckSize - acc.first, boxType.boxes)
(acc.first + count) to (acc.second + count * boxType.units)
} else {
acc
}
2022-07-14 15:28:35 +02:00
}
.second
2022-07-14 15:28:35 +02:00
}