Boats To Save People Problem
Description
LeetCode Problem 881.
You are given an array people where people[i] is the weight of the i^th person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person.
Example 1:
Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)
Example 2:
Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)
Example 3:
Input: people = [3,5,3,4], limit = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)
Constraints:
- 1 <= people.length <= 5 * 10^4
- 1 <= people[i] <= limit <= 3 * 10^4
Solution
Approach: Greedy with Two Pointers
Sort the weights. Then look at the heaviest person who is still waiting: they need a boat now, and the best partner for them is the lightest person left, since that is the partner most likely to fit.
- If the lightest and the heaviest together are at most
limit, they share a boat. - Otherwise nobody can share with the heaviest (everyone else weighs at least as much as the lightest), so they go alone.
Why this is optimal: take a best plan where the heaviest person H shares a boat with some x, and the lightest person L shares with some y (or rides alone). Swap x and L. Then H + L <= H + x <= limit, and x + y <= x + H <= limit because y <= H. The number of boats is unchanged, so some best plan pairs H with L.
Steps:
- Sort
people. - Keep
lightat the start andheavyat the end. - While
light <= heavy: ifpeople[light] + people[heavy] <= limit, movelightforward. Always moveheavyback and count one boat.
The loop condition is <=, not <: when light == heavy, one person is left and still needs a boat.
Complexity: O(n log n) time for the sort and O(1) extra space besides the sort, where n is the length of people.
class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
light, heavy = 0, len(people) - 1
boats = 0
while light <= heavy:
# The heaviest person always leaves now; the lightest joins if they fit.
if people[light] + people[heavy] <= limit:
light += 1
heavy -= 1
boats += 1
return boats
Now write it from memory
Close the write-up and solve it yourself against the tests.