Skip to content

Commit 653cfde

Browse files
authored
Merge pull request #1957 from andynullwong/0881
Create 0881-boats-to-save-people.js
2 parents 0e099bd + 8f39bbb commit 653cfde

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {number[]} people
3+
* @param {number} limit
4+
* @return {number}
5+
*/
6+
var numRescueBoats = function (people, limit) {
7+
const sortedPeople = people.sort((a, b) => a - b);
8+
let left = 0;
9+
let right = people.length - 1;
10+
let boats = 0;
11+
12+
while (left <= right) {
13+
const weight = sortedPeople[left] + sortedPeople[right];
14+
if (left === right || weight <= limit) {
15+
left++;
16+
right--;
17+
} else {
18+
right--;
19+
}
20+
boats++;
21+
}
22+
return boats;
23+
};

0 commit comments

Comments
 (0)