The Boats to Save People problem involves determining the minimum number of boats required to save people, given that each boat can carry at most two people and has a weight limit.
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people); // Sort people by weight
int left = 0, right = people.length - 1;
int boats = 0;
while (left <= right) {
if (people[left] + people[right] <= limit) {
left++; // Pair the lightest and heaviest person
}
right--; // Always use a boat for the heaviest person
boats++;
}
return boats;
}
}
O(N log N)
, where N
is the number of people.O(N)
, for iterating through the array.O(N log N)
.Input: people = [3, 2, 2, 1], limit = 3
Output: 3
Explanation:
- Boat 1: [1, 2]
- Boat 2: [2]
- Boat 3: [3]