To minimize boats, we should pair the heaviest person with the lightest person if possible. If the sum exceeds the limit, the heaviest person must go in a boat alone.
- Sort
people. l = 0,r = len(people) - 1,boats = 0.- While
l <= r:- If
people[l] + people[r] <= limit:l += 1(pair found).
r -= 1(heavy person always takes a boat).boats += 1.
- If
- Return
boats.
- Time Complexity: O(N log N).
- Space Complexity: O(1).
def num_rescue_boats(people, limit):
people.sort()
l, r = 0, len(people) - 1
boats = 0
while l <= r:
if people[l] + people[r] <= limit:
l += 1
r -= 1
boats += 1
return boats