101 Logo
onenoughtone

Code Implementation

Rescue Boat Dispatcher Implementation

Below is the implementation of the rescue boat dispatcher:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Greedy Approach with Two Pointers
* Time Complexity: O(n log n) - Dominated by the sorting operation
* Space Complexity: O(1) - Constant extra space
*
* @param {number[]} people - Array of people's weights
* @param {number} limit - Maximum weight each boat can carry
* @return {number} - Minimum number of boats needed
*/
function numRescueBoats(people, limit) {
// Sort the array in ascending order
people.sort((a, b) => a - b);
// Initialize pointers and counter
let i = 0; // lightest person
let j = people.length - 1; // heaviest person
let boats = 0;
// Process all people
while (i <= j) {
// If lightest and heaviest can share a boat
if (people[i] + people[j] <= limit) {
i++; // Move to next lightest person
}
j--; // Move to next heaviest person
boats++; // Count this boat
}
return boats;
}
// Test cases
console.log(numRescueBoats([1, 2], 3)); // 1
console.log(numRescueBoats([3, 2, 2, 1], 3)); // 3
console.log(numRescueBoats([3, 5, 3, 4], 5)); // 4

Step-by-Step Explanation

Let's break down the implementation:

  1. 1. Understand the Problem: First, understand that we need to find the minimum number of boats to rescue everyone, where each boat can carry at most 2 people and has a weight limit.
  2. 2. Sort the Array: Sort the array of people's weights in ascending order to facilitate the greedy approach.
  3. 3. Initialize Pointers: Set up two pointers: one at the beginning (lightest person) and one at the end (heaviest person).
  4. 4. Implement the Greedy Approach: Try to pair the lightest person with the heaviest person if their combined weight doesn't exceed the limit. Otherwise, the heaviest person takes a boat alone.
  5. 5. Count Boats: Increment the boat counter for each boat used, whether it carries one or two people.
  6. 6. Return the Result: Return the total number of boats needed to rescue everyone.
  7. 7. Test with Examples: Verify the solution with the provided examples and edge cases.
ProblemSolutionCode
101 Logo
onenoughtone