Boats to Save People
Difficulty: Medium · Pattern: Two Pointers · LeetCode #881
people[i] is the weight of person i. Each boat carries at most two people whose total weight is at most limit (every single person fits alone). Return the minimum number of boats.
Examples
text
people = [3, 2, 2, 1], limit = 3 → 3 ([1,2], [2], [3])
people = [3, 5, 3, 4], limit = 5 → 4
people = [1, 2], limit = 3 → 1Hints
- The heaviest person needs a boat no matter what. Who is the best partner for them?
- Sort, then use pointers at the lightest and the heaviest.
Approach
Sort the weights. The heaviest remaining person always takes a boat. If the lightest remaining person fits with them (people[l] + people[r] ≤ limit), send both; otherwise the heaviest goes alone. Pairing the heaviest with the lightest is optimal: if the lightest can't ride with the heaviest, nobody can.
Complexity
Time: O(n log n). Space: O(1) extra (ignoring sort).
Python solution
def numRescueBoats(people, limit):
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 boatsJavaScript solution
function numRescueBoats(people, limit) {
people.sort((a, b) => a - b);
let l = 0, r = people.length - 1, boats = 0;
while (l <= r) {
if (people[l] + people[r] <= limit) l++;
r--; boats++;
}
return boats;
}