Skip to main content

Command Palette

Search for a command to run...

boats save

Published
1 min readView as Markdown
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;
    }
}

More from this blog

Amit singh's blog

235 posts