problems: add maximum units on a truck
This commit is contained in:
parent
7929858e64
commit
852221b295
1 changed files with 19 additions and 0 deletions
19
problems/maximum-units-on-a-truck.kt
Normal file
19
problems/maximum-units-on-a-truck.kt
Normal file
|
@ -0,0 +1,19 @@
|
|||
class Solution {
|
||||
data class BoxType(val boxes: Int, val units: Int)
|
||||
fun toBoxType(x: IntArray): BoxType = BoxType(x[0], x[1])
|
||||
|
||||
fun maximumUnits(boxTypes: Array<IntArray>, truckSize: Int): Int =
|
||||
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
|
||||
}
|
||||
}
|
||||
.second
|
||||
}
|
Loading…
Reference in a new issue