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.