Edited: C++ solution, 9ms, O(1) space, O(n) time


  • 0
    X
    class Solution {
    public:
        int maxProduct(int A[], int n) {
    		int _max = INT_MIN;
    		int lastMinus = 0;
    		int res = 1;
    		for(int i = 0; i < n; ++i)
    		{
    			res *= A[i];
    			if(0 == res)
    			{
    				if(_max < res) _max = res;
    				lastMinus = 0;
    				res = 1;
    			}
    			else if(res > 0)
    			{
    				if(_max < res) _max = res;
    			}
    			else
    			{
    				if(0 == lastMinus)
    				{
    					lastMinus = res;
    					if(_max < res) _max = res;
    				}
    				else
    				{
    					if(_max < res/lastMinus) _max = res/lastMinus;
    				}
    			}
    		}
    		return _max;
    	}
    };

Log in to reply
 

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