O(n)time C++solution beats 99.8%


  • 0
    S
    class Solution {
    public:
    	int maximumProduct(vector<int>& nums) {
    		if (nums.size() == 3) return nums[0] * nums[1] * nums[2];
    		int a[5] = {-1001,-1001,-1001,1001,1001};
    		int i;
    		for (i = 0; i < nums.size(); i++)
    		{
    				if ((nums[i]>a[0])) a[0] = nums[i];
    				if (a[0] > a[1]) swap(a[0], a[1]);
    				if (a[1] > a[2]) swap(a[1], a[2]);
    				if ((nums[i] < a[3])) a[3] = nums[i];
    				if (a[3] < a[4]) swap(a[3], a[4]);
    		}
    		return max(a[0]*a[1]*a[2],a[2]*a[3]*a[4]);
    	}
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.