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 that a boat can carry. Each boat can carry at most two people at the same time, provided the sum of their weights is within the limit
. Return the minimum number of boats required to carry every person.
To solve this problem efficiently, we can use a two-pointer technique after sorting the array of people’s weights:
people
array.left
and right
) to represent the lightest and heaviest person, respectively.limit
, move both pointers inward (i.e., left++
and right--
).right
pointer inward (i.e., right--
), indicating that the heaviest person must go alone in a boat.people
array?Here is the C++ implementation:
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
int left = 0, right = people.size() - 1;
int boats = 0;
while (left <= right) {
if (people[left] + people[right] <= limit) {
// They can share a boat
left++;
right--;
} else {
// The heaviest person goes alone
right--;
}
boats++;
}
return boats;
}
};
O(n log n)
where n
is the number of elements in the people
array.O(n)
since each person is considered exactly once.Thus, the overall time complexity is dominated by the sorting step, resulting in O(n log n).
O(n)
for std::sort
in the worst case.O(1)
.Therefore, the overall space complexity is O(n) due to the sorting step.
Feel free to ask if you need further clarifications or if there are specific edge cases you’d like to discuss!
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?