Algo-Sim › Greedy

Boats to Save People

Medium · Greedy · step through it in Java, Python and C++ on your own input

Boats carry at most two people under a weight limit. Sort, then pair the heaviest person left with the lightest whenever they fit.

Problem

You are given people, where people[i] is the weight of the i-th person, and an unlimited number of boats that each carry at most two people with a total weight of at most limit. Return the minimum number of boats needed to carry everyone.

Constraints

Edge cases to test

Follow-up questions

Why pair the heaviest with the lightest?
If the heaviest can’t go with the lightest, they can’t go with anyone. If they can, pairing them is never worse: exchange argument.
What if the weights are small integers?
Counting sort instead of a comparison sort: O(n + limit).

Solution

Java

public int numRescueBoats(int[] people, int limit) {
    Arrays.sort(people);
    int boats = 0, lo = 0, hi = people.length - 1;
    while (lo <= hi) {
        if (people[lo] + people[hi] <= limit) lo++;
        hi--;
        boats++;
    }
    return boats;
}

Python

def num_rescue_boats(people, limit):
    people = sorted(people)
    boats, lo, hi = 0, 0, len(people) - 1
    while lo <= hi:
        if people[lo] + people[hi] <= limit:
            lo += 1
        hi -= 1
        boats += 1
    return boats

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int numRescueBoats(vector<int> &people, int limit) {
        sort(people.begin(), people.end());
        int boats = 0, lo = 0, hi = int(people.size()) - 1;
        while (lo <= hi) {
            if (people[lo] + people[hi] <= limit) lo++;
            hi--;
            boats++;
        }
        return boats;
    }
};

More Greedy problems