[LeetCode] Maximum Product Subarray, leetcodesubarray
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.
This problem is to find a subsequence in the array, and requires that the product of the number in this subsequence is the largest of all subsequences.
If efficiency and optimization are not considered, you can list the combinations of all subsequences, calculate their product, and obtain the maximum value. As follows:
int maxProduct(int A[], int n) { int i = 0, j = 0,k=0; int ans = 0; int product = 0; for (i = n; i > 0; i--){ for (j = 0; j <= n-i; j++){ for (k = j; k < i; k++){ product += A[k]; } if (product>ans){ ans = product; } product = 0; } } return ans; }
However, the efficiency is very low. In another way, we can think of this question as "local optimization and global optimization" in one-dimensional dynamic planning ". Therefore, we need to maintain two variables: the maximum value and the minimum value of the Continuous Product of the current position.
The maximum and minimum values can be obtained from the following three conditions: the last curMax * A [I], the last curMin * A [I], and A [I. As follows:
int maxProduct(int A[], int n) { int ans = A[0]; int curMin = A[0]; int curMax = A[0]; int cur = 1; for (int i = 1; i < n; i++){ cur = curMax; curMax = max(max(A[i],A[i]*curMax),A[i]*curMin); curMin = min(min(A[i], A[i] * cur), A[i] * curMin); ans = max(ans, curMax); } return ans; }