You are given an array people where
Return the minimum number of boats to carry every given person.
Output: 1
Explanation: 1 boat can carry both (1, 2) since the limit is 3.
Output: 3
Explanation: 3 boats (1, 2), (2) and (3).
Output: 4
Explanation: 4 boats (3), (3), (4), (5).
Constraints:
1 <= people.length <= 5 * 104 1 <= people[i] <= limit <= 3 * 104
Contents
Solution 1 - Sort input array, then place people into boats with mix of higher and lower weights
The main intution behind this solution is, since we have people with mix of weights in the array, inorder to ulitize minimum number of boats,
we first have fit maximum weight people and if there is still room, then fit low weight people with a maximum of two people and total weight is
less than or equal to
Say if
- First, we can place
3 into one boat, because the next element is 2, but the limit is4 . - Next, we will place
2 into next boat. - Then,
4 in another boat - Next,
1 in a separate boat.
So, in this approach we will sort the input array first, then mix people with higher weights and lower weights if there is room. Let's apply the solution above problem.
- After sorting the array it will become
[1,2,3,4] - First, we will take the highest weight from right side, which is 4, we will put this person into 1st boat, since there is no room after placing this person, we cannot add any smaller weight people.
-
Then, take the next highest weight from right side, which is 3, place this person into 2nd boat,
since there is still room for weight 1, check the lowest weight from left side, which is 1, this can fit into the same boat,
so the second boat will carry
(3, 1) weights. - Remaining weight is 2, we wil place this into a separate boat.
- So, total minimum number of boats required are 3.
Complexity Analysis:
Time complexity: Above code runs in O(n log n) time where
Space complexity: O(1).
Above implementations source code can be found at