You are given an array people where people[i] is the weight of the iᵗʰ 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.
Sort the people by weight. For each unboarded heaviest person, scan through the remaining people to find the heaviest one that can share their boat.
people.Why it's not optimal: The inner scan is O(n), making the whole approach O(n²). Two pointers achieves the same greedy pairing in O(n) after sorting.
def numRescueBoats(people, limit): people.sort() boarded = [False] * len(people) boats = 0 for i in range(len(people) - 1, -1, -1): if boarded[i]: continue boarded[i] = True for j in range(0, i): if not boarded[j] and people[i] + people[j] <= limit: boarded[j] = True; break boats += 1 return boats
After sorting, use two pointers at both ends. The heaviest person always takes a boat. If they can share with the lightest remaining person (sum ≤ limit), pair them. Otherwise the heaviest goes alone. Either way, one boat is used and we move R left.
people. Set L=0, R=n-1, boats=0.L <= R: if people[L] + people[R] <= limit, both board — L++.R and increment boats.
Discussion
…