Maximum Product Subarray问题及解法

问题描述:

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

示例

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

问题分析:

我们设maxi[i]表示以i为结尾的值最大子数组的积,mini[i]表示以i为结尾的值最小子数组的积,则根据定义maxi[i + 1] = max(nums[i + 1], max(maxi[i] * nums[i + 1], mini[i] * nums[i + 1])),mini[i + 1] = min(nums[i + 1], min(maxi[i] * nums[i + 1], mini[i] * nums[i + 1]))。


过程详见代码:

class Solution {
public:
    int maxProduct(vector& nums) {
        int n = nums.size();
		if (!n) return 0;
		vector maxi(n, 0);
		vector mini(n, 0);
		int res = nums[0];
		maxi[0] = nums[0];
		mini[0] = nums[0];
		for (int i = 1; i < n; i++)
		{
			maxi[i] = max(nums[i], max(maxi[i - 1] * nums[i], mini[i - 1] * nums[i]));
			mini[i] = min(nums[i], min(maxi[i - 1] * nums[i], mini[i - 1] * nums[i]));
			res = max(res, maxi[i]);
		}
		return res;
    }
};


你可能感兴趣的:(Maximum Product Subarray问题及解法)