Boats to Save People

medium two pointers greedy sorting

Problem

Each boat carries at most two people, as long as their combined weight is within limit. Given the weights people and the limit, return the minimum number of boats needed to carry everyone.

Inputpeople = [3, 2, 2, 1], limit = 3
Output3
Boats: (1,2), (2), (3).

def num_rescue_boats(people, limit):
    people.sort()
    lo, hi, boats = 0, len(people) - 1, 0
    while lo <= hi:
        if people[lo] + people[hi] <= limit:
            lo += 1
        hi -= 1
        boats += 1
    return boats
function numRescueBoats(people, limit) {
  people.sort((a, b) => a - b);
  let lo = 0, hi = people.length - 1, boats = 0;
  while (lo <= hi) {
    if (people[lo] + people[hi] <= limit) lo++;
    hi--;
    boats++;
  }
  return boats;
}
int numRescueBoats(int[] people, int limit) {
    Arrays.sort(people);
    int lo = 0, hi = people.length - 1, boats = 0;
    while (lo <= hi) {
        if (people[lo] + people[hi] <= limit) lo++;
        hi--;
        boats++;
    }
    return boats;
}
int numRescueBoats(vector<int>& people, int limit) {
    sort(people.begin(), people.end());
    int lo = 0, hi = people.size() - 1, boats = 0;
    while (lo <= hi) {
        if (people[lo] + people[hi] <= limit) lo++;
        hi--;
        boats++;
    }
    return boats;
}
Time: O(n log n) Space: O(1)