Skip to content

Commit 9b86dcb

Browse files
committedMar 22, 2025
Add solution #881
1 parent 63c7927 commit 9b86dcb

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,7 @@
691691
878|[Nth Magical Number](./0878-nth-magical-number.js)|Hard|
692692
879|[Profitable Schemes](./0879-profitable-schemes.js)|Hard|
693693
880|[Decoded String at Index](./0880-decoded-string-at-index.js)|Medium|
694+
881|[Boats to Save People](./0881-boats-to-save-people.js)|Medium|
694695
884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy|
695696
889|[Construct Binary Tree from Preorder and Postorder Traversal](./0889-construct-binary-tree-from-preorder-and-postorder-traversal.js)|Medium|
696697
890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium|
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 881. Boats to Save People
3+
* https://leetcode.com/problems/boats-to-save-people/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array people where people[i] is the weight of the ith person, and an infinite
7+
* number of boats where each boat can carry a maximum weight of limit. Each boat carries at
8+
* most two people at the same time, provided the sum of the weight of those people is at most
9+
* limit.
10+
*
11+
* Return the minimum number of boats to carry every given person.
12+
*/
13+
14+
/**
15+
* @param {number[]} people
16+
* @param {number} limit
17+
* @return {number}
18+
*/
19+
var numRescueBoats = function(people, limit) {
20+
people.sort((a, b) => a - b);
21+
let boats = 0;
22+
let left = 0;
23+
let right = people.length - 1;
24+
25+
while (left <= right) {
26+
if (left < right && people[left] + people[right] <= limit) {
27+
left++;
28+
right--;
29+
} else {
30+
right--;
31+
}
32+
boats++;
33+
}
34+
35+
return boats;
36+
};

0 commit comments

Comments
 (0)
Please sign in to comment.