You are given an array people
where people[i]
is the weight of the ith person, and an integer limit
representing the weight limit of a boat. Each boat can carry at most two people at the same time, provided the sum of the weights of those people is at most limit
.
Return the minimum number of boats to carry every person.
limit
.The problem can be effectively solved using a two-pointer technique combined with sorting:
people
to organize the weights.left
at index 0) and the other from the heaviest person (right
at index len(people) - 1
).limit
). If they can, move both pointers inward; if they can’t, move only the right
pointer inward as the heaviest person will need a separate boat.def numRescueBoats(people, limit):
people.sort()
left, right = 0, len(people) - 1
boats = 0
while left <= right:
if people[left] + people[right] <= limit:
left += 1 # This person can share the boat
right -= 1
boats += 1 # A boat is used
return boats
people
array is sorted, which helps easily pair the lightest and heaviest people.left
pointer starts at the beginning (lightest person) and the right
pointer starts at the end (heaviest person).left
and right
is within the boat limit, increment the left
pointer (indicating this person is on the boat).right
pointer (indicating the heaviest person is accounted for).boats
count for each valid operation (moving in the pointers).Thus, the overall time complexity is O(N log N) due to the sorting step. The two-pointer scan is linear in complexity afterward, which is efficient for most practical input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?