[LeetCode] Boats to Save People

881. Boats to Save People

You are given an array people where people[i] is the weight of the ith person, and 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 the minimum number of boats to carry every given person.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
multiset<int> p(people.begin(), people.end());
int res = 0;
while(!p.empty()) {
auto ma = prev(end(p));
int mi = limit - *ma;
p.erase(ma);
if(mi != 0) {
auto it = p.upper_bound(mi);
if(it != begin(p)) {
p.erase(prev(it));
}
}
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/24/PS/LeetCode/boats-to-save-people/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.