From 155b63cc56bd5a5793623cdb7fba043ca3afaf9c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 4 May 2024 11:35:52 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB881.=20Boats=20to=20Save=20?= =?UTF-8?q?People=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/boats-to-save-people.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 java/boats-to-save-people.java diff --git a/java/boats-to-save-people.java b/java/boats-to-save-people.java new file mode 100644 index 0000000..676bb3f --- /dev/null +++ b/java/boats-to-save-people.java @@ -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; + } +}