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.
1def
In a Pythonic way, the code iterates with dual indices to balance boats' weight limitations through sorted entries, preventing unnecessary boat use and serving a comprehensive solution efficiently.