881. Boats to Save People
Asked at 12Amazon43Bloomberg34Google29Meta29Microsoft20Sigmoid87IBM50Cognizant48Walmart Labs43Snowflake39DE Shaw38tcs27
Problem
people[i] is a person's weight. Every boat carries at most two people with combined weight ≤ limit, and nobody is heavier than limit. Return the minimum number of boats needed for everyone.
Example: people = [3,2,2,1], limit = 3 → 3 ((1,2), (2), (3))
Constraints: n ≤ 5·10⁴.
Sort. The heaviest person always takes a boat; pair them with the lightest if they fit together.
Complexity: O(n log n).
class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
l, r, boats = 0, len(people) - 1, 0
while l <= r:
if people[l] + people[r] <= limit:
l += 1
r -= 1
boats += 1
return boats
assert Solution().numRescueBoats([3, 2, 2, 1], 3) == 3
assert Solution().numRescueBoats([3, 5, 3, 4], 5) == 4
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int l = 0, r = people.length - 1, boats = 0;
while (l <= r) {
if (people[l] + people[r] <= limit) l++;
r--;
boats++;
}
return boats;
}
}
func numRescueBoats(people []int, limit int) int {
sort.Ints(people)
boats := 0
for l, r := 0, len(people)-1; l <= r; r-- { // the heaviest always leaves
if people[l]+people[r] <= limit {
l++ // ...with the lightest if they fit
}
boats++
}
return boats
}