首页 > 代码库 > DP Leetcode - Maximum Product Subarray

DP Leetcode - Maximum Product Subarray

最近一直忙着写paper,很久没做题,一下子把题目搞复杂了。。思路理清楚了非常简单,每次只需更新2个值:当前子序列最大乘积和当前子序列的最小乘积。最大乘积被更新有三种可能:当前A[i]>0,乘以前面最大的数(>0),得到新的最大乘积;当前A[i]<0,乘以前面最小的数(<0),得到新的最大乘积;A[i]它自己>0,(A[i-1]==0。最小乘积同理。。


class Solution {
public:

	int Max(int a, int b, int c)
	{
		int max = -1 << 30;

		if (a >= b)
			max = a;
		else
			max = 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;
		else
			min = 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