The Fastest solution given in "Complete Solution" is wrong. Here's why (correct me if I'm wrong though)


#1

The solution given in the editorial for “Complete Solution” for “Fastest” is:

int Solution::solve(vector &A)
{
int n=A.size();
int maxm=A[0],minm=A[0];
for(int i=1;i<n;i++)
{
if(A[i]>maxm) maxm=A[i];
else if(A[i]<minm) minm=A[i];
}
return maxm+minm;
}

However, it fails to account for an entire positive array. I guess because that’s the most basic test case and won’t be integrated. Hence for [1,2,3,4] test case, this solution fails and returns 5 instead of a 3.

I think this should be the code: (This accounts for the above test case also)

int Solution::solve(vector &A)
{
int n=A.size();
int maxm=A[0],minm=A[0];
for(int i=1;i<n;i++)
{
if(A[i]>maxm) maxm=A[i];
else if(A[i]<minm) minm=A[i];
}
if(minm>0) return maxm-minm;
else return maxm+minm;

}

Kindly correct me if I’m wrong. Really curious about this though.


#2

To me it looks like you don’t understand the problem. For array [1,2,3,4] , the solution is 5 and not 3. Reasoning: Max element: 4 and min Element: 1, so max + min = 4+1 = 5.