Greedy Algorithms8 sections · 316 units
Open in Course

Boats - Algorithm

Two-pointer pairing

Sort by weight. Use two pointers: lightest (left) and heaviest (right).

If they fit together (sum <= limit), pair them. Both pointers move inward.

If not, the heaviest goes alone. Only right pointer moves. It works because the heaviest person must go on some boat. Pairing them with the lightest maximizes space efficiency. Time: O(nlogn)O(n \log n). Space: O(1)O(1). Common bug: not moving both pointers when pairing succeeds, which double-counts people.