Problem 307459 · medium · Level 03 Linear Management & Searching

Minimum Shipping Crates

two pointers · greedy · sorting

A warehouse packs boxes into crates. Every crate holds at most two boxes, and the boxes in a crate must weigh at most limit in total. Given a list weights (each weights[i] <= limit), return the minimum number of crates needed to pack every box.

Examples

Input:  weights = [5, 2, 6, 3, 4, 7], limit = 8
Output: 4
Explanation: crates {2, 6}, {3, 5}, {4}, {7}.

Input:  weights = [6, 4, 7, 5], limit = 7
Output: 4
Explanation: no two boxes fit together.

Constraints

  • 0 <= len(weights) <= 10**5
  • 1 <= weights[i] <= limit <= 10**6
  • Target: O(n log n) time (sorting), then a single O(n) scan.

Goals

  • Pair the heaviest remaining item with the lightest when possible
  • Prove to yourself why the greedy pairing is never worse
Starting Python…