File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments