Boats to Save People — LeetCode 881 Python Solution
- Problem
- #881
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an array people where people[i] is the weight of the ith 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.
Example
- Input
- people = [1,2], limit = 3
- Output
- 1
- Explanation
- 1 boat (1, 2)
Python solution
class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
ans = 0
i, j = 0, len(people) - 1
while i <= j:
if people[i] + people[j] <= limit:
i += 1
j -= 1
ans += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 881. Boats to Save People is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 881. Boats to Save People?
- LeetCode 881. Boats to Save People is rated Medium on LeetCode.
- What is the time complexity of LeetCode 881. Boats to Save People?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 881. Boats to Save People?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 881. Boats to Save People cover?
- LeetCode 881. Boats to Save People is tagged Greedy, Array, Two Pointers and Sorting on LeetCode.