boats save
class Solution {
public int numRescueBoats(int[] people, int limit) {
// Step 1: Sort the array
Arrays.sort(people);
// Two pointers
int left = 0; // lightest person
int right = people.length - 1; // heaviest person
int boats = 0; // count boat
// Step 2: Move both pointers towards each other
while (left <= right) {
// Try to pair the lightest with the heaviest
if (people[left] + people[right] <= limit) {
left++; // lightest person is taken
}
// Heaviest person always goes (alone or paired)
right--;
// We used one boat
boats++;
}
return boats;
}
}