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
- 1 ≤ people.length ≤ 5 · 10⁴
- 1 ≤ people[i] ≤ limit ≤ 3 · 10⁴
- At most two people per boat
Edge cases to test
- Everyone fits alone only
- Two people exactly at the limit
- One person
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 boatsC++
#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
- Maximum Subarray (Medium)
- Best Time to Buy and Sell Stock II (Medium)
- Jump Game (Medium)
- Jump Game II (Medium)
- Gas Station (Medium)
- Partition Labels (Medium)
- Task Scheduler (Medium)
- Hand of Straights (Medium)
- Merge Triplets to Form Target Triplet (Medium)
- Valid Parenthesis String (Medium)
- Minimum Number of Arrows to Burst Balloons (Medium)
- Candy (Hard)
- Two City Scheduling (Medium)