SDE & MLE Prep

881. Boats to Save People

Problem

people[i] is a person's weight. Every boat carries at most two people with combined weight ≤ limit, and nobody is heavier than limit. Return the minimum number of boats needed for everyone.

Example: people = [3,2,2,1], limit = 3 → 3 ((1,2), (2), (3))

Constraints: n ≤ 5·10⁴.

Sort. The heaviest person always takes a boat; pair them with the lightest if they fit together.

Complexity: O(n log n).

class Solution:
    def numRescueBoats(self, people: List[int], limit: int) -> int:
        people.sort()
        l, r, boats = 0, len(people) - 1, 0
        while l <= r:
            if people[l] + people[r] <= limit:
                l += 1
            r -= 1
            boats += 1
        return boats