- Related Questions & Answers
- Where do waste goes from the ships or boats?
- How to save an Image in OpenCV using C++?
- Distribute Candies to People in Python
- How to save an Android Activity state using save instance state?
- Java Program to save decimal
- Group the People Given the Group Size They Belong To in C++
- How to save password in android webview?
- How to use save() correctly in MongoDB?
- Why people prefer smartphones to laptops nowadays?
- How to save time in milliseconds in MySQL?
- Program to recover shuffled queue of people in python
- How to save data using sqlite in android?
- How to save canvas data to file in HTML5?
- How can you make people listen to you?
- Best ways to discover people to talk on twitter

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

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 −

#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)); }

[3,2,1,2] 3

3

Advertisements