I have been busy writing paper recently. I haven't done any questions for a long time, and I have complicated my questions .. The logic is very simple. You only need to update two values at a time: the maximum product of the current subsequence and the Minimum Product of the current subsequence. There are three possibilities for updating the Maximum Product: current A [I]> 0, multiplied by the previous maximum number (> 0) to obtain the new maximum product; current A [I] <0, multiply the first smallest number (<0) to obtain the new maximum product; a [I] It itself> 0, (a [I-1] = 0. The same is true for the minimum product ..
class Solution {public:int Max(int a, int b, int c){int max = -1 << 30;if (a >= b)max = a;elsemax = b;if (c > max)max = c;return max;}int Min(int a, int b, int c){int min = 1 << 30;if (a <= b)min = a;elsemin = b;if (c < min)min = c;return min;}int maxProduct(int A[], int n) {int maxPPrev=A[0], maxP;int minPPrev = A[0], minP;int max = A[0];for (int i = 1; i < n; i++){maxP = Max(maxPPrev * A[i], minPPrev * A[i], A[i]);minP = Min(maxPPrev * A[i], minPPrev * A[i], A[i]);maxPPrev = maxP;minPPrev = minP;if (maxPPrev > max)max = maxPPrev;if (minPPrev > max)max = minPPrev;}return max;}};
DP leetcode-Maximum Product subarray