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.

分析:

        此题类似编程之美2.14、求数组的子数组之和的最大值。采用动态规划的方法,先找出动态规划的递推式,动态规划的解法无非是维护两个变量,局部最优和全局最优。在做乘法的时候,需要保存局部最大值max和局部最小值min,因为如果A[i]为负数,有可能最大数来自min*A[i]。因此每次在max*A[i]、min*A[i]、A[i]中取最大值作为局部最优解max,同时更新最小值min和全局最优解。

代码实现:

#include"stdafx.h"
#include <iostream>

using namespace std;

class Solution {  
public:
	struct Pair
	{
		int max;
		int min;
	};
	int maxProduct(int A[],int n)
	{  
		if(n==0)
			return 0;
		if(n==1)
			return A[0];
		Pair local;
		local.max=A[0];
		local.min=A[0];
		int result=A[0];

		for(int i=1;i<n;i++)
		{	
			local=get_pair(local,A[i]);
			if(local.max>result)
				result=local.max;
		}
		return result;
	}
	Pair get_pair(Pair x,int y)
	{
		Pair temp;
	    int a=x.max*y;
	    int b=x.min*y;
		if(a>b){
			temp.max=a;
			temp.min=b;
		}
		else{
			temp.max=b;
			temp.min=a;
		}
		if(y>temp.max)
			temp.max=y;
		else if(y<temp.min)
			temp.min=y;
		return temp;
	}
}; 
void main()
{
	int A[9]={-1,2,3,4,5,0,7,11,10};
	Solution s;
	cout<<s.maxProduct(A,9)<<endl;
	getchar();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值