- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Boats to Save People in C++

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

#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

- Related Articles
- Who invented boats?
- Name the agency in India who advises people how to save petrol/diesel. What tips are given by them
- How to save an Image in OpenCV using C++?
- C++ Program to find rounded numbers to save kingdom
- Where do waste goes from the ships or boats?
- Distribute Candies to People in Python
- How to save an Android Activity state using save instance state?
- Group the People Given the Group Size They Belong To in C++
- Find the Number of Ways to Pair People using C++
- How to save password in android webview?
- How to use save() correctly in MongoDB?
- Java Program to save decimal
- How to save time in milliseconds in MySQL?
- Two boats approach a light house in mid-sea from opposite directions. The angles of elevation of the top of the light house from two boats are ( 30^{circ} ) and ( 45^{circ} ) respectively. If the distance between two boats is ( 100 mathrm{~m} ), find the height of the light house.
- How to save canvas data to file in HTML5?

Advertisements