In the Boats to Save People coding problem, you are given an array representing the weights of people and a weight limit for each boat. Each boat can carry at most two people at the same time, provided their combined weight doesn't exceed the limit. Your goal is to find the minimum number of boats required to carry everyone.
This is a popular medium-level question at companies like Microsoft, Amazon, and Google. It tests your ability to identify the correct strategy for optimization. While it might look like a dynamic programming problem at first, it's actually perfectly suited for a Greedy approach. It also evaluates your skill in using Two Pointers to traverse a sorted array efficiently.
This problem uses the Greedy pattern combined with the Two Pointers interview pattern. The greedy strategy is to always try to pair the heaviest person currently available with the lightest person. If they can both fit, great; if not, the heaviest person must take a boat by themselves (as they are the most likely to exceed the limit with anyone else). By sorting the array first, you can use one pointer at the start (lightest) and one at the end (heaviest) to make these decisions in time.
Array: [1, 2, 2, 3], Limit: 3
[1, 2, 2, 3].left = 0 (val 1), right = 3 (val 3).right becomes 2).right becomes 1, left becomes 1).A common mistake is trying to pair the two lightest people first, which is not optimal. Another error is forgetting the constraint that only two people can fit in a boat. Some candidates also forget to sort the array, which is a mandatory step for the two-pointer approach to work.
Whenever you encounter an optimization problem involving "minimum number of X to cover Y," always consider if a Greedy strategy works before jumping into more complex DP. Sorting is often the key to making greedy choices obvious.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Bag of Tokens | Medium | Solve | |
| Maximum Matching of Players With Trainers | Medium | Solve | |
| Minimize Maximum Pair Sum in Array | Medium | Solve | |
| Pancake Sorting | Medium | Solve | |
| Maximize Greatness of an Array | Medium | Solve |