C++ O(n) solution without sorting


#1

int Solution::maxp3(vector &nums) {
int m1=INT_MIN,m2=INT_MIN,m3=INT_MIN;
int s1=INT_MAX,s2=INT_MAX;
for(int i=0;i<nums.size();i++){
//updating max 3 elements
if(nums[i]>m3){
m1=m2;
m2=m3;
m3=nums[i];
}
else if(nums[i]>m2){
m1=m2;
m2=nums[i];
}
else if(nums[i]>m1){
m1=nums[i];
}
//updating minimum 2 elements
if(nums[i]<s1){
s2=s1;
s1=nums[i];
}
else if(nums[i]<s2){
s2=nums[i];
}
}
return max(m1m2m3,m3s1s2);
}