881. Boats to Save People LeetCode Solution
In this guide, you will get 881. Boats to Save People LeetCode Solution with the best time and space complexity. The solution to Boats to Save People problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Boats to Save People solution in C++
- Boats to Save People solution in Java
- Boats to Save People solution in Python
- Additional Resources

Problem Statement of Boats to Save People
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.
Return the minimum number of boats to carry every given person.
Example 1:
Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)
Example 2:
Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)
Example 3:
Input: people = [3,5,3,4], limit = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)
Constraints:
1 <= people.length <= 5 * 104
1 <= people[i] <= limit <= 3 * 104
Complexity Analysis
- Time Complexity: O(\texttt{sort})
- Space Complexity: O(\texttt{sort})
881. Boats to Save People LeetCode Solution in C++
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
int ans = 0;
ranges::sort(people);
for (int i = 0, j = people.size() - 1; i <= j; ++ans) {
const int remain = limit - people[j--];
if (people[i] <= remain)
++i;
}
return ans;
}
};
/* code provided by PROGIEZ */
881. Boats to Save People LeetCode Solution in Java
class Solution {
public int numRescueBoats(int[] people, int limit) {
int ans = 0;
Arrays.sort(people);
for (int i = 0, j = people.length - 1; i <= j; ++ans) {
final int remain = limit - people[j--];
if (people[i] <= remain)
++i;
}
return ans;
}
}
// code provided by PROGIEZ
881. Boats to Save People LeetCode Solution in Python
class Solution:
def numRescueBoats(self, people: list[int], limit: int) -> int:
ans = 0
i = 0
j = len(people) - 1
people.sort()
while i <= j:
remain = limit - people[j]
j -= 1
if people[i] <= remain:
i += 1
ans += 1
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.