Skip to content

Commit 42eb54b

Browse files
authored
Merge pull request #1874 from adelajaOlamilekan/main
Solved 0881-boats-to-save-people in c++
2 parents 66ac5a3 + 5f7fe72 commit 42eb54b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Diff for: cpp/0881-boats-to-save-people.cpp

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

0 commit comments

Comments
 (0)