forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0881-boats-to-save-people.cpp
38 lines (32 loc) · 1.19 KB
/
0881-boats-to-save-people.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
Given an array of people's weight, people[i] is the weight of the ith person,
and there is an infinite number of boats where each boat can carry a maximum weight of limit.
Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.
Return minimum number of boats to carry every given person.
sort, while there is people to carry
carry the heaviest and lightest person provided their weight doesn't exceed limit.
otherwise, carry the heaviest person only
Time: O(n)
Space: O(1)
*/
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
int boatRequired = 0;
int lightestPerson = 0;
int heaviestPerson = people.size()-1;
//WHILE THERE IS SOMEONE TO CARRY
while (lightestPerson <= heaviestPerson){
if(people[lightestPerson] + people[heaviestPerson] <= limit){
--heaviestPerson;
++lightestPerson;
}
else{
--heaviestPerson;
}
++boatRequired;
}
return boatRequired;
}
};