Skip to content

Boats to Save People

MediumTwo Pointers
Decode it first. Clues, constraints, pattern and plan before any code.

You are given a list people where people[i] is the weight of person i, and an unlimited number of boats. Each boat can carry at most two people at the same time, as long as their total weight is at most limit. Return the minimum number of boats needed to carry everyone.

people = [1, 2],       limit = 3   →  1   (both fit in one boat)
people = [3, 2, 2, 1], limit = 3   →  3   ((1, 2), (2), (3))
people = [3, 5, 3, 4], limit = 5   →  4   (nobody can share)

Constraints

  • 1 <= people.length <= 5 * 10^4
  • 1 <= people[i] <= limit <= 3 * 10^4