|
| 1 | +# https://leetcode.com/problems/maximum-units-on-a-truck/ |
| 2 | + |
| 3 | + |
| 4 | +import timeit |
| 5 | +from typing import List |
| 6 | + |
| 7 | +# Runtime: 238 ms, faster than 50.64% of Python3 online submissions for Maximum Units on a Truck. |
| 8 | +# Memory Usage: 14.4 MB, less than 83.07 % of Python3 online submissions for Maximum Units on a Truck. |
| 9 | + |
| 10 | + |
| 11 | +class Solution: |
| 12 | + def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: |
| 13 | + # Sort by units per box to maximize the units of the boxes we pick |
| 14 | + boxTypes.sort(key=lambda x: (x[1]), reverse=True) |
| 15 | + remaining_space, units_loaded = truckSize, 0 |
| 16 | + for boxes_of_type, units_per_box in boxTypes: |
| 17 | + # Add as many as possible of the current type |
| 18 | + can_load = min(boxes_of_type, remaining_space) |
| 19 | + remaining_space -= can_load |
| 20 | + units_loaded += can_load * units_per_box |
| 21 | + if remaining_space == 0: |
| 22 | + break |
| 23 | + return units_loaded |
| 24 | + |
| 25 | + |
| 26 | +def test(): |
| 27 | + executor = [ |
| 28 | + {'executor': Solution, 'title': 'Solution', }, |
| 29 | + ] |
| 30 | + tests = [ |
| 31 | + [[[1, 3], [2, 2], [3, 1]], 4, 8], |
| 32 | + [[[5, 10], [2, 5], [4, 7], [3, 9]], 10, 91], |
| 33 | + ] |
| 34 | + for e in executor: |
| 35 | + start = timeit.default_timer() |
| 36 | + for _ in range(int(float('1'))): |
| 37 | + for t in tests: |
| 38 | + sol = e['executor']() |
| 39 | + result = sol.maximumUnits(t[0], t[1]) |
| 40 | + expected = t[2] |
| 41 | + assert result == expected, f'{result} != {expected} for {t[0]}:{t[1]} using {e["title"]} solution' |
| 42 | + used = str(round(timeit.default_timer() - start, 5)) |
| 43 | + result = "{0:20}{1:10}{2:10}".format(e['title'], used, "seconds") |
| 44 | + print(f"\033[92m» {result}\033[0m") |
| 45 | + |
| 46 | + |
| 47 | +test() |
0 commit comments