152. 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(vector& nums) {
		//vectormaxSub(nums);
		int localMax = nums[0];
		int localMin = nums[0];
		int gmax = localMax;
		for (int i = 1; i < nums.size(); i++){
			int tmp = localMax;
			localMax = max(max(localMax*nums[i], nums[i]), localMin*nums[i]);
			localMin = min(min(localMin*nums[i], nums[i]), tmp*nums[i]);

			if (localMax > gmax){
				gmax = localMax;
			}
		}
		return gmax;
	}
};


你可能感兴趣的:(leetcode)