LeetCode Solutions

881. Boats to Save People

Time:

Space:

			

class Solution {
 public:
  int numRescueBoats(vector<int>& people, int limit) {
    int ans = 0;

    sort(begin(people), end(people));

    for (int i = 0, j = people.size() - 1; i <= j; ++ans) {
      int remain = limit - people[j--];
      if (people[i] <= remain)
        ++i;
    }

    return ans;
  }
};
			

class Solution {
  public int numRescueBoats(int[] people, int limit) {
    int ans = 0;

    Arrays.sort(people);

    for (int i = 0, j = people.length - 1; i <= j; ++ans) {
      int remain = limit - people[j--];
      if (people[i] <= remain)
        ++i;
    }

    return ans;
  }
}
			

class Solution:
  def numRescueBoats(self, people: List[int], limit: int) -> int:
    ans = 0
    i = 0
    j = len(people) - 1

    people.sort()

    while i <= j:
      remain = limit - people[j]
      j -= 1
      if people[i] <= remain:
        i += 1
      ans += 1

    return ans