Python coding

Fewest two-seat boats

weights[i] is the weight of person i. Every boat carries at most two people, and their total weight must not exceed limit. Nobody weighs more than limit, and there are as many boats as you need. Return the fewest boats that carry everyone.

weights may be empty and may repeat values. Sorting is fine; after it, aim for one O(n) pass instead of searching for each person's partner.

Besides the tests, one large input (3,800 people) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • fewest_boats([70,50,80,50], 100) → 3
  • fewest_boats([1,2,8,9], 10) → 2
  • fewest_boats([1,1,1,1], 5) → 2
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Sort, then think about the heaviest person left. They need a boat now, and the best companion to try is the lightest person left.

Hint 2

Keep lo on the lightest and hi on the heaviest. If the two fit, both board; if not, nobody fits with hi, so hi rides alone. Either way hi moves inward.

Solution and why it works
pythonO(n log n) for the sort, then O(n) · O(n) for the sorted copy
def fewest_boats(weights: list[int], limit: int) -> int:
    w = sorted(weights)
    lo, hi = 0, len(w) - 1
    boats = 0
    while lo <= hi:
        if w[lo] + w[hi] <= limit:   # the lightest left can ride with the heaviest
            lo += 1
        hi -= 1                      # the heaviest leaves now, alone or paired
        boats += 1
    return boats

After sorting, look at the heaviest person left. If even the lightest one left cannot ride with them, nobody can, so they go alone. If the lightest fits, pairing them is safe: any best plan can be changed to seat the lightest next to them without adding a boat or breaking the limit. Each step settles hi and maybe lo, so the pass is O(n). Trap: pairing light people with each other first wastes the seats the heavy ones need ([1, 2, 8, 9], limit 10).

Related lab: Loops in motion