Simple Cpp solution without sorting O(n)


#1

int Solution::maxp3(vector &A) {
int l1=INT_MIN,l2=INT_MIN;
int s1=INT_MAX,s2=INT_MAX;
int large=INT_MIN,index;
//finding largest number in the array
//if largest==0 then ans becomes 0
for(int i=0;i<A.size();i++){
if(large<A[i]){
index=i;
large=A[i];
}
}
if(large==0)
return 0;
//finding two smallest no.s in the array as s1 and s2
//finding two largest no.s in the array(excluding the index of the above found “large”)as l1 and l2
for(int i=0;i<A.size();i++){
if(i==index)
continue;
if(l1<=l2 and l1<=A[i])
l1=A[i];
else if(l2<=l1 and l2<=A[i])
l2=A[i];
if(s1>=s2 and s1>=A[i])
s1=A[i];
else if(s2>=s1 and s2>=A[i])
s2=A[i];
}
if(large>0)
return large * max(l1l2,s1s2);
return large * min(l1l2,s1s2);
}