l at the lightest, r at the heaviest. If they fit, l++. Always r−− and count a boat.
Approach 1
import java.util.Arrays;
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int l = 0, r = people.length - 1, boats = 0;
while (l <= r) {
if (people[l] + people[r] <= limit) l++;
r--;
boats++;
}
return boats;
}
}
Verdict: Exchange argument on the heaviest person.
Before you submit
Edge cases and common mistakes
Test these inputs
Everyone at the limit (n boats)
One person
Mistakes people make
Pairing the two lightest (wastes light partners the heavy ones need).