 # Boats to save people

https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/580/week-2-january-8th-january-14th/3602/

Can anyone explain Why Iam getting Runtime Error?

this link does not allow to see other people code

class Solution {
public:
int numRescueBoats(vector& people, int limit) {

``````   int start=0,k=2,boat=0;
sort(people.begin(),people.end());
int a=people.size();
while(start<a)
{
int sum=0;
sum=people[start]+people[start+1];
if(sum<=limit)
{
boat++;
start+=2;

}
else
{
boat++;
start+=1;
}
}
return boat;

}
``````

};

if size = 1, then what would happen?

You can use simple 2 pointer approach on a sorted array to solve this problem.

Haa.But wanted to know why the above code doesnot works.

if start is n-1 then start + 1 will be n, Which is an invalid index if it is 0 based indexing.

1 Like

Even though correcting the above error,the code passes only half of the test cases.

class Solution {
public:
int numRescueBoats(vector& people, int limit) {

``````   sort(people.begin(),people.end());
int n=people.size();
vector<int> vis(n,0);
int nob=0;
for(int i=0;i<n;i++)
{
if(!vis[i])
{
int j=n-1;
while(vis[j]==1 && j>0)
{
j--;
}
while(i<j)
{
if(people[i]+people[j]<=limit)
{
nob++;
vis[i]=1;
vis[j]=1;
break;
}
else
{
j--;
while(vis[j]==1 && j>0)
{
j--;
}
}
}
if(i==j)
{
nob++;
vis[i]=1;
}
}
}
return nob;
}
``````

};

I have implemented using two point approach here.For some testcases I am getting TLE.

Have a look at my code below, you will get your mistake.

``````class Solution {
public:
int numRescueBoats(vector<int>& people, int limit)
{
sort(people.begin(),people.end());
int i=0,j=people.size()-1,c=0;
while(i<=j)
{
if(people[i]+people[j]<=limit)
{
c++;
i++;
j--;
}
else
{
j--;
c++;
}
}
return c;
}
};``````
1 Like