problems(cpp): add “881. Boats to Save People”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
ec2b3df836
commit
1388a820e7
1 changed files with 27 additions and 0 deletions
27
problems/boats-to-save-people.cpp
Normal file
27
problems/boats-to-save-people.cpp
Normal file
|
@ -0,0 +1,27 @@
|
|||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int numRescueBoats(std::vector<int> people, int limit)
|
||||
{
|
||||
std::sort(people.begin(), people.end());
|
||||
|
||||
int counter = 0;
|
||||
|
||||
std::size_t left = 0, right = people.size() - 1;
|
||||
while (left <= right && left < people.size() && right < people.size()) {
|
||||
counter++;
|
||||
|
||||
// if they both it, shift the left pointer
|
||||
if (left < right && people[left] + people[right] <= limit) {
|
||||
left++;
|
||||
}
|
||||
|
||||
// anyways, at least the heaviest person is included
|
||||
right--;
|
||||
}
|
||||
|
||||
return counter;
|
||||
}
|
||||
};
|
Loading…
Reference in a new issue