881. Boats to Save People #196
-
Topics: You are given an array Return the minimum number of boats to carry every given person. Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a two-pointer greedy strategy combined with sorting. Here's the detailed approach:
Let's implement this solution in PHP: 881. Boats to Save People <?php
function numRescueBoats($people, $limit) {
sort($people); // Step 1: Sort the array
$left = 0; // Pointer for the lightest person
$right = count($people) - 1; // Pointer for the heaviest person
$boats = 0;
// Step 2: Use two pointers to try and pair people
while ($left <= $right) {
if ($people[$left] + $people[$right] <= $limit) {
// If they can share a boat, move both pointers
$left++;
}
// Whether they share or not, the heaviest person takes a boat
$right--;
$boats++; // Count the boat used
}
return $boats; // Return the total number of boats
}
// Test cases
echo numRescueBoats([1, 2], 3); // Output: 1
echo "\n";
echo numRescueBoats([3, 2, 2, 1], 3); // Output: 3
echo "\n";
echo numRescueBoats([3, 5, 3, 4], 5); // Output: 4
?> Explanation:
Time Complexity:
Thus, the overall time complexity is Space Complexity:
Example Walkthrough:For the input: $people = [3,5,3,4]; $limit = 5;
Thus, the final output is |
Beta Was this translation helpful? Give feedback.
We can use a two-pointer greedy strategy combined with sorting. Here's the detailed approach:
Sort the Array:
people
array. Sorting helps us to easily pair the lightest and heaviest person together in one boat, if possible.Two Pointer Strategy:
left
), and the other starting from the heaviest person (right
).right
) with the lightest person (left
). If the sum of their weights is less than or equal to the limit, they can share the same boat. Move both pointers (left++
andright--
).right
pointer (r…