码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_152题——Maximum Product Subarray(动态规划)

时间:2015-07-09 22:38:22      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

Maximum Product Subarray

 Total Accepted: 33022 Total Submissions: 170218My Submissions

 

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.

 

Hide Tags
 Array Dynamic Programming
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

 

而对于Product Subarray,要考虑到一种特殊情况,即负数和负数相乘:如果前面得到一个较小的负数,和后面一个较大的负数相乘,得到的反而是一个较大的数,如{2,-3,-7},所以,我们在处理乘法的时候,除了需要维护一个局部最大值,同时还要维护一个局部最小值,由此,可以写出如下的转移方程式:

max_copy[i] = max_local[i]
max_local[i + 1] = Max(Max(max_local[i] * A[i], A[i]),  min_local * A[i])

min_local[i + 1] = Min(Min(max_copy[i] * A[i], A[i]),  min_local * A[i])

#include<iostream>
#include<vector>
#include<math.h>
using namespace std;


int maxProduct(vector<int>& nums)
{
	int len=nums.size();
	if(len==1)
		return nums[0];

	int maxm=nums[0];
	int minm=nums[0];
	int re=nums[0];
	for(int i=1;i<len;i++)
	{
		int a=max(max(maxm*nums[i],nums[i]),minm*nums[i]);
		int b=min(min(maxm*nums[i],nums[i]),minm*nums[i]);
		if(a>re)
			re=a;
		if(b>re)
			re=b;
		maxm=a;
		minm=b;
	}
	return re;
}

int main()
{
	int ary[4]={2,3,-2,4};
	vector<int> vec(ary,ary+4);
	cout<<maxProduct(vec)<<endl;
}

  

leetcode_152题——Maximum Product Subarray(动态规划)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4634395.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!