101 Logo
onenoughtone

Solution Approach

Solution Overview

There are 1 main approaches to solve this problem:

  1. Greedy Approach with Two Pointers - Complex approach

Approach 1: Greedy Approach with Two Pointers

Let's start by understanding the problem: 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.

Thinking Process: Since each boat can carry at most 2 people, we want to optimize how we pair people to minimize the number of boats. A greedy approach would be to try to pair the heaviest person with the lightest person, if possible.

If the heaviest person and the lightest person can fit in one boat (i.e., their combined weight is less than or equal to the limit), we put them in the same boat. Otherwise, the heaviest person must take a boat alone.

Intuition: By sorting the array and using two pointers (one at the beginning for the lightest person and one at the end for the heaviest person), we can efficiently implement this greedy approach.

Algorithm:

  1. Sort the array of people's weights in ascending order.
  2. Initialize two pointers: i at the beginning (lightest person) and j at the end (heaviest person).
  3. Initialize a counter for the number of boats needed.
  4. While i <= j (there are still people to rescue):
  5. a. If people[i] + people[j] <= limit, then the lightest and heaviest person can share a boat:
  6. i. Increment i (move to the next lightest person).
  7. b. Decrement j (move to the next heaviest person, regardless of whether they shared a boat).
  8. c. Increment the boat counter.
  9. Return the boat counter.

Time Complexity:

O(n log n)

The time complexity is dominated by the sorting operation, which takes O(n log n) time. The two-pointer traversal takes O(n) time.

Space Complexity:

O(1)

We only use a constant amount of extra space regardless of the input size (ignoring the space required for sorting, which depends on the implementation).

Pseudocode

solution.pseudo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function numRescueBoats(people, limit):
// Sort the array in ascending order
sort(people)
// Initialize pointers and counter
i = 0 // lightest person
j = people.length - 1 // heaviest person
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
ProblemSolutionCode
101 Logo
onenoughtone