From 8f39bbbd0c6dcba183c0862033fd658821200b3c Mon Sep 17 00:00:00 2001 From: Andy Wong Date: Sat, 7 Jan 2023 19:55:00 -0500 Subject: [PATCH] Create 0881-boats-to-save-people.js --- javascript/0881-boats-to-save-people.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 javascript/0881-boats-to-save-people.js diff --git a/javascript/0881-boats-to-save-people.js b/javascript/0881-boats-to-save-people.js new file mode 100644 index 000000000..59e6b57cc --- /dev/null +++ b/javascript/0881-boats-to-save-people.js @@ -0,0 +1,23 @@ +/** + * @param {number[]} people + * @param {number} limit + * @return {number} + */ +var numRescueBoats = function (people, limit) { + const sortedPeople = people.sort((a, b) => a - b); + let left = 0; + let right = people.length - 1; + let boats = 0; + + while (left <= right) { + const weight = sortedPeople[left] + sortedPeople[right]; + if (left === right || weight <= limit) { + left++; + right--; + } else { + right--; + } + boats++; + } + return boats; +};