Leetcode 881: Boats to Save People

grid47
grid47
Exploring patterns and algorithms
Aug 10, 2024 6 min read

You are given a list of people where each person has a certain weight, and a boat with a weight limit. Each boat can carry at most two people at the same time, as long as their combined weight does not exceed the boat’s weight limit. Your task is to determine the minimum number of boats required to rescue everyone.
Problem
Approach
Steps
Complexity
Input: You are given an array of integers where each integer represents the weight of a person. You are also given a weight limit that each boat can carry.
Example: Input: people = [2, 3, 5, 8], limit = 8
Constraints:
• 1 <= people.length <= 5 * 10^4
• 1 <= people[i] <= limit <= 3 * 10^4
Output: You should return a single integer, which represents the minimum number of boats required to carry all the people.
Example: Output: 3
Constraints:
• The output is a single integer.
Goal: The goal is to minimize the number of boats used while ensuring that no boat carries more than its weight limit.
Steps:
• Sort the list of people by their weight.
• Use a two-pointer technique where one pointer starts at the lightest person and the other starts at the heaviest.
• If the combined weight of the two people is within the limit, they can share a boat.
• If not, the heavier person takes a boat alone.
• Continue this process until all people have been assigned to a boat.
Goal: The problem must be solved within the constraints of the problem size and time efficiency.
Steps:
• The solution must run efficiently for up to 50,000 people.
• The algorithm must handle large values for the weight limit (up to 30,000).
Assumptions:
• The input array contains weights of people that range between 1 and the boat's limit.
• There are no edge cases where a person weighs more than the boat's limit, as this will never be the case based on the constraints.
Input: Input: people = [2, 3, 5, 8], limit = 8
Explanation: The sorted people array is [2, 3, 5, 8]. The heaviest person (8) takes a boat alone, the next pair (2, 5) can share a boat, leaving 3 to take a boat on their own. Hence, 3 boats are needed.

Input: Input: people = [4, 2, 6, 3], limit = 7
Explanation: The sorted people array is [2, 3, 4, 6]. The pair (2, 6) shares a boat, and the pair (3, 4) shares a boat. Hence, 2 boats are needed.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus