881. Boats to Save People
Solution
Try to match the heaviest one and lightest one in the queue, if possible. if not, then let the heaviest one go along.
Sort the people array first so that we can do that by simply tracing the start pointer(start from 0) and the end pointer (start from the end of the array)
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int count = 0, i = 0, j = people.length-1;
while( i <= j){
if(people[i] + people[j] <= limit){
i++;
j--;
}else{
j--;
}
count++;
}
return count;
}
Last updated
Was this helpful?