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.
1using System;
2
3public class RescueBoats {
4 public int NumRescueBoats(int[] people, int limit) {
5 Array.Sort(people);
6 int i = 0, j = people.Length - 1;
7 int boats = 0;
8 while (i <= j) {
9 if (people[i] + people[j] <= limit) i++;
10 j--;
11 boats++;
12 }
13 return boats;
14 }
15 public static void Main() {
16 int[] people = {3, 2, 2, 1};
17 int limit = 3;
18 RescueBoats rb = new RescueBoats();
19 Console.WriteLine(rb.NumRescueBoats(people, limit));
20 }
21}
C# leverages Array.Sort for sorting. With two pointers, it explores potential pairings between the smallest and largest weights, optimizing boat usage under a limited weight capacity.
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.
1import
Utilizing a greedy mechanism, Java's sorting and pointer steps ensure every person fits optimally into boats, recognizing when sole riding becomes necessary due to capacity limits.