Greedy Flashcards

(1 cards)

1
Q

Boats to Save People

You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.

Return the minimum number of boats to carry every given person.

Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)

A

Sort the array and greedily try to pair up the lightest and heaviest people left

    Arrays.sort(people);
    int left=0, right=people.length-1;
    int result = 0;
    while(left <= right) {
        if (people[left] + people[right] <= limit) {
            left++;
            right--;
        } else {
            right--; //put the heavier person on this, lighter person can
            //likely be clubbed with another
        }
        result++;
    }
    return result;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly