โ† Back to Index

๐Ÿ“š Boats to Save People โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Boats to Save People problem involves determining the minimum number of boats required to save people, given that each boat can carry at most two people and has a weight limit.

๐Ÿงฑ Pattern Template

Two-Pointer Greedy Algorithm

class Solution {
    public int numRescueBoats(int[] people, int limit) {
        Arrays.sort(people); // Sort people by weight
        int left = 0, right = people.length - 1;
        int boats = 0;

        while (left <= right) {
            if (people[left] + people[right] <= limit) {
                left++; // Pair the lightest and heaviest person
            }
            right--; // Always use a boat for the heaviest person
            boats++;
        }

        return boats;
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example

Input: people = [3, 2, 2, 1], limit = 3
Output: 3

Explanation:
- Boat 1: [1, 2]
- Boat 2: [2]
- Boat 3: [3]

๐Ÿ’ก Pro Tips