#1710

Maximum Units on a Truck

Easy Fractional-knapsack style

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Box types come as [count, unitsPerBox]. A truck holds at most truckSize boxes. Maximise the total units loaded.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: load boxes to maximise units, limited by the number of boxes.

Why this works: every box uses one slot, so take the boxes with the most units first.

Example: [[1,3],[2,2],[3,1]], truck 4

1 box × 3, 2 boxes × 2, 1 box × 13 + 4 + 1 = 8

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Sorting by box count instead of units per box.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n).
  • Space: O(log n) for sorting.
Topic: Greedy
🎬 Episodes 69–73: video coming soon