File: maximum-units-on-a-truck/solution.py

Date: 2026-06-06

Time: 17:44

maximum-units-on-a-truck/solution.py

Purpose

Solves LeetCode 1710 — Maximum Units on a Truck. Given box types (each with a count and units-per-box) and a truck capacity in boxes, it returns the maximum total units the truck can carry. This is a classic greedy problem: prioritize boxes with the highest unit density.

Key Components

busiest_servers(boxTypes, truckSize) -> int — The sole function. Despite its name, it has nothing to do with "busiest servers" (LeetCode 1606). The function name is a copy-paste error; it should be maximumUnits to match the LeetCode problem signature.

Contract:

Patterns

Greedy sort-then-scan. Sort by the value axis (units per box) in descending order, then iterate once, greedily taking as many boxes as possible from each type. This is the canonical greedy pattern for fractional-knapsack-like problems where items are fully divisible by count.

Dependencies

Imports: None — pure function, no external dependencies.

Imported by: The "Imported By" list in the context is misleading. The hundreds of test files listed are from unrelated problems — this is likely an artifact of the test infrastructure or static analysis tooling, not a real dependency graph for this module. The genuine consumer is maximum-units-on-a-truck/test_solution.py.

Flow

1. Sort in-placeboxTypes.sort(key=lambda x: x[1], reverse=True) orders by units-per-box descending. This mutates the caller's list.

2. Greedy scan — iterate through sorted box types; for each, take min(availableboxes, remainingcapacity).

3. Accumulate — add take * unitsperbox to running total, decrement remaining capacity.

4. Early exit — break when remaining == 0 (truck is full).

Invariants

Error Handling

None. No input validation. Negative truckSize, empty boxTypes, or negative counts would produce silently wrong results rather than exceptions.