Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit42eb54b

Browse files
authored
Merge pull requestneetcode-gh#1874 from adelajaOlamilekan/main
Solved 0881-boats-to-save-people in c++
2 parents66ac5a3 +5f7fe72 commit42eb54b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎cpp/0881-boats-to-save-people.cpp‎

Lines changed: 38 additions & 0 deletions
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+
classSolution {
16+
public:
17+
intnumRescueBoats(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)

[8]ページ先頭

©2009-2025 Movatter.jp