Boats to Save People

Minimum boats to ferry people with weight limit — sort, pair heaviest with lightest if they fit.

Medium
Time O(n log n) Space O(1)
LeetCode
2 min read
greedy two-pointers sorting

Problem#

Each boat takes at most 2 people with total weight ≤ limit. Return minimum boats to ferry everyone.

Examples#

  • people = [1,2], limit = 31
  • people = [3,2,2,1], limit = 33

Constraints#

  • 1 <= n <= 5 * 10^4.

Approach#

Sort. Two pointers l (lightest) and r (heaviest). If they fit together, take both; else send heaviest alone. Count boats.

Solution#

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

Editorial#

The heaviest person always takes one boat. The greedy decision is whether to also send the lightest with them. If they fit, pair them — never worse than wasting a half-boat on the heaviest alone. If not, the lightest will pair with someone else later, but the heaviest’s boat is fixed.

Complexity#

  • Time: O(n log n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.