# Boats to Save People in C++

C++Server Side ProgrammingProgramming

Suppose we have an array called people. Now the i-th person has weight people[i], and each boat can carry a maximum weight of limit. If each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit. We have to find the minimum number of boats to carry every given person. So if the input is like [3,2,1,2], and limit is 3, then we need three boats. [(1,2), (2), (3)].

To solve this, we will follow these steps −

• sort the people array

• i := 0, j := size of people array – 1, ret := 0

• while i <= j

• if people[i] + people[j] <= limit, then i := i + 1 and j := j – 1, otherwise j := j – 1

• ret := ret + 1

• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
int i = 0;
int j = people.size() - 1;
int ret = 0;
while(i <= j){
if(people[i] + people[j] <= limit){
i++, j--;
}else{
j--;
}
ret++;
}
return ret;
}
};
main(){
vector<int> v = {3,2,1,2};
Solution ob;
cout << (ob.numRescueBoats(v, 3));
}

### Input

[3,2,1,2]
3

## Output

3
Published on 10-Apr-2020 13:18:12