Greedy Algorithms8 sections · 316 units
Open in Course

Boats - Implementation

The code

function numRescueBoats(people, limit)
 sort people ascending
 left := 0
 right := length of people - 1
 boats := 0
 while left <= right
 if people[left] + people[right] <= limit then
 left := left + 1
 right := right - 1
 boats := boats + 1
 return boats

Time: O(nlogn)O(n \log n). Space: O(1)O(1) extra.