Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

class Solution {
public:
    int maxProduct(int A[], int n) {
        int result = A[0];
	    if (n == 1)
	    {
		    return result;
	    }
	    int tempMax = A[0];
	    int tempMin = A[0];
	    for (int i = 1; i < n; i++)
	    {
	        int prevMax = tempMax;
		    tempMax = max(max(A[i], A[i]*tempMax), A[i]*tempMin);
		    tempMin = min(min(A[i], A[i]*prevMax), A[i]*tempMin);
		    if (tempMax > result)
		    {
			    result = tempMax;
		    }
	    }

	    return result;
    }
};


你可能感兴趣的:(Maximum Product Subarray)