Skip to the content

The lifeboats

Problem

After the shipwreck, the lifeboats shuttle back and forth between the ship and the shore. Each boat carries two people at most, and together they can't go over the weight it holds. Every trip takes time, so you want everyone off with as few boats as possible.

Write a function that takes weights, a list of positive integers that may be empty, and limit, the weight one boat holds. Nobody weighs more than limit, and exactly at the limit still fits. Return the fewest boats, as an integer; with nobody to rescue, 0.

With [70, 50, 80, 50] and limit 100: the two 50s go together, the 70 goes alone and the 80 goes alone. That's 3 boats.

Examples

  • The example

    [70, 50, 80, 50], 100 → 3

  • Pairs right at the limit

    [5, 1, 4, 2], 6 → 2

  • Only two per boat

    [10, 10, 10, 10, 10], 100 → 3

  • A single person

    [60], 100 → 1

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def boats(weights, limit):
    pass

JavaScript

function boats(weights, limit) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n log n) challenges

See all challenges →