Leetcode 881. Boats to Save People
You are given an array people
where people[i]
is the weight of the i-th
person, and an integer limit
which represents the maximum weight a boat can carry. Each boat can carry no more than two people at the same time, provided the sum of weights of those people is at most limit
.
Your task is to find the minimum number of boats required to carry every given person.
Q: Can a person be on more than one boat? A: No, each person must be on exactly one boat.
Q: Can there be a scenario where it is impossible to fit a person within the given weight limit? A: No, you can assume that it is always possible to save everyone.
Q: Can the input array be empty?
A: Since the problem asks to find the minimum number of boats to save people, we can assume the input array people
will have at least one element.
Q: How should we handle edge cases, like when all people have the same weight? A: The solution should account for all edge cases. Sorting the array will help manage such scenarios.
i
) starts from the beginning (lightest person) and another pointer (j
) starts from the end (heaviest person).import java.util.Arrays;
public class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int i = 0;
int j = people.length - 1;
int boats = 0;
while (i <= j) {
// If the lightest and the heaviest person can be in the same boat
if (people[i] + people[j] <= limit) {
i++;
j--;
} else {
// Only the heaviest person takes a boat
j--;
}
boats++;
}
return boats;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] people1 = {1, 2};
int limit1 = 3;
System.out.println(solution.numRescueBoats(people1, limit1)); // Output: 1
int[] people2 = {3, 2, 2, 1};
int limit2 = 3;
System.out.println(solution.numRescueBoats(people2, limit2)); // Output: 3
int[] people3 = {3, 5, 3, 4};
int limit3 = 5;
System.out.println(solution.numRescueBoats(people3, limit3)); // Output: 4
}
}
O(n log n)
, where n
is the number of people.O(n)
, as each person is considered at most once.Therefore, the overall time complexity is O(n log n)
due to the sorting step.
O(1)
for the sorting and two-pointer operations, excluding the input space.This solution is efficient and handles the problem requirements within optimal time and space constraints.
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?