Boats to Save People

MediumGreedyLeetCode 881 ↗World 7-14
0:00 / 0:00

Each boat holds two people under a weight limit. Sort, then pair the heaviest with the lightest when they fit; otherwise the heaviest rides alone.

▼

The problem

LeetCode 881 (Medium). people[i] is a person's weight. Each boat carries at most two people at once, as long as their total weight is at most limit (nobody weighs more than limit). Return the minimum number of boats that carry everyone.

The example on screen (made up): people = [2, 7, 1, 5, 4, 6], limit = 7 → 4 boats: (7), (1, 6), (2, 5), (4). Sorted it is 1 2 4 5 6 7; the run: 1 + 7 = 8 > 7, the 7 rides alone; 1 + 6 = 7 fits, they share; 2 + 5 = 7 fits; left = right, the 4 rides alone.

The slow ways shown: trying every pairing (the card counts the ways to split n people into boats of one or two, the involution numbers: 76 for 6 people, 46,206,736 for 16; it flickers through all 76 pairings of the crowd); and a quick greedy without sorting (each person, in the given order, takes the first later person who still fits): the 2 takes the 1, then no two of 7, 5, 4, 6 fit together, so 5 boats where 4 will do.

def num_rescue_boats(people, limit):
    people.sort()
    left, right = 0, len(people) - 1
    boats = 0
    while left <= right:
        if people[left] + people[right] <= limit:
            left += 1      # the lightest rides along
        right -= 1         # the heaviest always boards
        boats += 1
    return boats

Checked against a brute force (best pairing by bitmask search) on 30,000 random inputs (n 1 to 8, limit 1 to 12), and on LeetCode's examples ([1,2], 3 → 1; [3,2,2,1], 3 → 3; [3,5,3,4], 5 → 4). Every number on screen is computed in code at load time (solve, firstFit, brute and pairings in src/rescue.jsx; each scene asserts the values it shows, and src/gen_score.py re-runs the solution for its cue table). O(n log n) time for the sort plus one O(n) pass; O(1) extra space beyond the sort.

TRY IT ON LEETCODE ▶

The solution

def num_rescue_boats(people, limit):
    people.sort()
    left, right = 0, len(people) - 1
    boats = 0
    while left <= right:
        if people[left] + people[right] <= limit:
            left += 1      # the lightest rides along
        right -= 1         # the heaviest always boards
        boats += 1
    return boats

Transcript

Boats to Save People. A flood, and people wait on a pier, each with a weight. Every boat carries at most two people, and their total weight can't go over the limit. Nobody weighs more than the limit on their own. What's the fewest boats that save everyone?

Here are six people, weighing two, seven, one, five, four and six. The limit is seven. One boat each would take six boats, but some can share: one and six make seven, and so do two and five. The fewest is four boats.

Trying every way to pair people up works, but the number of ways explodes: seventy-six for six people, over forty-six million for sixteen. A quick greedy fails too. Go down the line, and let each person take the first one who fits. Two grabs one, and then nobody else fits together. Five boats, one too many.

The key idea: sort, then look at the heaviest person. They need a boat no matter what. If anyone can share it, the lightest can, because everyone else is heavier. So when the lightest fits, they ride together. Otherwise the heaviest rides alone.

Sorted, the line is one, two, four, five, six, seven. One plus seven is eight, too heavy: seven rides alone. Now six: one plus six is seven, so they share boat two. Two plus five is seven, so they take boat three. Only four is left, and four rides alone. Four boats, and everyone is saved.

In code, sort the list and put a pointer at each end. While left hasn't passed right, check whether the lightest and the heaviest fit together. If they do, left steps in. Right always steps in, and we count one boat.

Sorting takes n log n time. After that, every boat takes the heaviest person left, so the pointers meet in one pass. Beyond the sort, we keep just two pointers and a count: constant extra space.

Sort, board the heaviest, add the lightest if they fit. That's Boats to Save People.