Sponsored
Sponsored
This approach utilizes sorting and a two-pointer technique. By sorting the array, we simplify the pairing process, always trying to pair the lightest and heaviest person possible to fit within the limit. This method is greedy because it always tries to use the lightest and heaviest pair that fits to use fewer boats.
Time Complexity: O(n log n) due to sorting. Space Complexity: O(1) since we're sorting in place.
1def num_rescue_boats(people, limit):
2 people.sort()
3 i, j = 0, len(people) - 1
4 boats = 0
5 while i <= j:
6 if people[i] + people[j] <= limit:
7 i += 1
8 j -= 1
9 boats += 1
10 return boats
11
12people = [3, 2, 2, 1]
13limit = 3
14print(num_rescue_boats(people, limit))
In Python, we first sort the people list. Using two pointers and a while loop, we attempt to pair individuals based on their weights to accommodate the maximum weight limit, increasing the boat count as needed.
In this approach, we again sort the weights, but the main focus is on maximizing each boat's capacity. If the heaviest person cannot be paired with the lightest one, they solely occupy a boat.
Time Complexity: O(n log n) - Primary time usage is the sorting step. Space Complexity: O(1) when sorting in-place.
1using System;
2
public class RescueBoatsGreedy {
public int NumRescueBoats(int[] people, int limit) {
Array.Sort(people);
int i = 0, j = people.Length - 1;
int boats = 0;
while (i <= j) {
if (people[i] + people[j] <= limit) {
i++;
}
j--;
boats++;
}
return boats;
}
public static void Main() {
int[] people = {3, 5, 3, 4};
int limit = 5;
RescueBoatsGreedy rb = new RescueBoatsGreedy();
Console.WriteLine(rb.NumRescueBoats(people, limit));
}
}
Through an organized sort approach and efficient weight management, this technique disseminates the heaviest persons solo when necessary, focusing on solution integrity and minimal vessel usage.