Table of contents
Techniques Used
- Greedy
- Two Pointer
- Sorting
Approach
- Sort the
people
weights array. - Now, use the two pointer technique to navigate the elements of
people
weights array. - while the
start
is less thanend
index, do the following:- if adding the weight at the
end
index is under the prescribedlimit
AND number of people on the current boat is less than or equal to 1 (people_on_curr_boat <= 1
)- add the person at the
end
index and increment the number of people on the current boat (people_on_curr_boat
) and increment the boat weight (curr_boat_size
) - if
boat_count
was 0, then increment theboat_count
. (Because we start with the boat_count of 0) - decrement the
end
Index.
- add the person at the
- else if (do the same above steps for the element at start index)
- else
- increment the
boat_count
. (as current boat is full and unable to accomodate further). - make the
curr_boat_size
as 0 because a new boat has been taken. - make the number of people on curr boat as 0. (
people_on_curr_boat = 0
)
- increment the
- if adding the weight at the
- Once you are outside this while loop, just return the
boat_count
.
Complexity
- Time Complexity: O(nlogn + n)
- logn for sorting.
- n for visiting each element only once, and processing it.
- Space Complexity: O(1) - We are not using any space that grows with n.
Note: Please let me know if I am wrong anywhere in my analysis.
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int end = people.length - 1;
int start = 0;
int curr_boat_size = 0;
int boat_count = 0;
int people_on_curr_boat = 0;
while(start <= end){
if(curr_boat_size + people[end] <= limit && people_on_curr_boat <= 1) {
people_on_curr_boat++;
curr_boat_size += people[end];
if(boat_count == 0) boat_count++;
end--;
}
else if(curr_boat_size + people[start] <= limit && people_on_curr_boat <= 1){
people_on_curr_boat++;
curr_boat_size += people[start];
if(boat_count == 0) boat_count++;
start++;
}
else {
boat_count++;
curr_boat_size = 0;
people_on_curr_boat = 0;
}
}
return boat_count;
}
}