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] ;
	int minEndWithNMinusOne=A[0];
	int maxEndWithNMinusOne=A[0];
	int maxNMinusOne=A[0];

	for(int i=1;i<n;i++){
		int tempMinEndWithNMinusOne = min(min(A[i],maxEndWithNMinusOne*A[i]),minEndWithNMinusOne*A[i]);//最小值的所有可能性
		maxEndWithNMinusOne = max(max(A[i],minEndWithNMinusOne*A[i]),maxEndWithNMinusOne*A[i]);
		result = max(tempMinEndWithNMinusOne,max(maxEndWithNMinusOne,result));
		minEndWithNMinusOne=tempMinEndWithNMinusOne;
	}
#ifdef DEBUG
    cout<<result<<endl;
#endif
	
	return result;
}
};

你可能感兴趣的:(动态规划)