From 7c60dee83b436e8e8a667bf9f191beced8de4fc3 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 00:36:13 -0600 Subject: chore: move cpp and rust code to directory --- other/boats_save_people.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 other/boats_save_people.cpp (limited to 'other/boats_save_people.cpp') diff --git a/other/boats_save_people.cpp b/other/boats_save_people.cpp new file mode 100644 index 0000000..7221191 --- /dev/null +++ b/other/boats_save_people.cpp @@ -0,0 +1,35 @@ +// 881. Boats to Save People +#include "leetcode.h" + +/* + * given an array 'people' where 'people[i]' is the weight of the i'th 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 minimum number + * of boats to carry every person + */ + +class Solution { +public: + int numRescueBoats(vector &people, int limit) { + sort(people.begin(), people.end()); + int max_weight = people.size() - 1, min_weight = 0, ans = 0; + while (min_weight <= max_weight) { + if (people[min_weight] + people[max_weight] <= limit) { + min_weight++; + max_weight--; + } else + max_weight--; + ans++; + } + return ans; + } +}; + +int main() { + Solution obj; + vector p1 = {1, 2}, p2 = {3, 2, 2, 1}, p3 = {3, 5, 3, 4}; + printf("%d\n", obj.numRescueBoats(p1, 3)); // expect: 1 + printf("%d\n", obj.numRescueBoats(p2, 3)); // expect: 3 + printf("%d\n", obj.numRescueBoats(p3, 5)); // expect: 4 +} -- cgit v1.2.3