From 852221b295359012a464982ec654d2f7c6e7d0f0 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 14 Jul 2022 13:28:35 +0000 Subject: [PATCH] problems: add maximum units on a truck --- problems/maximum-units-on-a-truck.kt | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 problems/maximum-units-on-a-truck.kt diff --git a/problems/maximum-units-on-a-truck.kt b/problems/maximum-units-on-a-truck.kt new file mode 100644 index 0000000..4c61be9 --- /dev/null +++ b/problems/maximum-units-on-a-truck.kt @@ -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, 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 +}