Skip to content
Problem 881 · LeetCode 881(opens in a new tab)

Boats to Save People

MediumGreedy

You are given the weights of some people, people, and the weight a boat can carry, limit. Every boat holds at most two people, and their total weight must be at most limit. Nobody weighs more than limit, so everyone fits in a boat alone.

Return the smallest number of boats needed to carry everyone.

Example 1

Input:  people = [4, 2, 5, 3], limit = 6
Output: 3
Why:    boats [5], [2, 4] and [3]
2 more examples and the constraints

Example 2

Input:  people = [3, 3, 3], limit = 3
Output: 3
Why:    any two together weigh 6, over the limit

Example 3

Input:  people = [1, 2, 2, 1], limit = 4
Output: 2
Why:    boats [1, 2] and [1, 2]

Constraints

  • 1 ≤ number of people ≤ 50,000
  • 1 ≤ each weight ≤ limit ≤ 30,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Heaviest first, scan for a partnerO(n²)
  2. Sort + two pointersO(n log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50,000 peopleVerdict
Heaviest first, scan for a partnerO(n²)
Correct, but slow when few pairs fit
Sort + two pointersO(n log n)
Best; one sort, one pass

n = how many people there are.

Edge cases to test

  • One person. [7] with limit 7 needs one boat.
  • Nobody can share. [3, 3, 3] with limit 3 needs three boats.
  • Exact fit. A pair whose total equals the limit is allowed: use ≤, not <.
  • Pointers meet. When lo equals hi one person is left; they need their own boat, so the loop runs while lo ≤ hi.

Common mistakes

  • Looping while lo < hi, which forgets the last person when the count is odd.
  • Trying to fit three people in a boat; the cap is two, whatever they weigh.
  • Pairing the two lightest people first, which can leave heavy people with nobody who fits.

How to talk through it

  1. 1Clarify. At most two per boat? Can anyone weigh more than the limit? (No.)
  2. 2Give the simple greedy. Heaviest first, scan for a partner: correct, but O(n²).
  3. 3Argue the pairing. The heaviest must go; the lightest is the only partner worth testing.
  4. 4Code the two pointers. Move lo only when the pair fits; move hi and count a boat every step.
  5. 5Test out loud. Run one person, an odd count, and a pair that fits exactly.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?