Skip to content

Commit 32b4595

Browse files
committed
Boats to Save People
1 parent f05a165 commit 32b4595

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

boats_to_save_people.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# https://leetcode.com/problems/boats-to-save-people/
2+
3+
# The i-th person has weight people[i], and each boat can carry a maximum weight of limit.
4+
# Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.
5+
# Return the minimum number of boats to carry every given person.
6+
# (It is guaranteed each person can be carried by a boat.)
7+
8+
"""
9+
>>> Solution().numRescueBoats([1, 2], 3)
10+
1
11+
>>> Solution().numRescueBoats([3, 2, 2, 1], 3)
12+
3
13+
>>> Solution().numRescueBoats([3, 5, 3, 4], 5)
14+
4
15+
"""
16+
from typing import List
17+
18+
19+
class Solution:
20+
def numRescueBoats(self, people: List[int], limit: int) -> int:
21+
num_boats = 0
22+
first_person = 0
23+
last_person = len(people) - 1
24+
25+
people.sort()
26+
while first_person <= last_person:
27+
if people[first_person] + people[last_person] <= limit:
28+
first_person += 1
29+
last_person -= 1
30+
else:
31+
last_person -= 1
32+
num_boats += 1
33+
34+
return num_boats

0 commit comments

Comments
 (0)