java: add «881. Boats to Save People»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-05-04 11:35:52 +02:00
parent 8222f5e1db
commit 155b63cc56
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,24 @@
import java.util.Arrays;
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.parallelSort(people);
int counter = 0;
int left = 0, right = people.length - 1;
while (left <= right && left < people.length && right >= 0) {
++counter;
// they both fit
if (left < right && people[left] + people[right] <= limit) {
++left;
}
// the heaviest person is always included
--right;
}
return counter;
}
}