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

Maximum Product Subarray

时间:2015-02-10 15:26:37      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:

动态规划.用一个二维数组表示下标从i至j的子数组的最大值实际就是将所有可能的组合方式的值都记录下来,然后比较选出最大的值在动态规划的过程中,由于负数的存在,在比较过程中只需记录最大值最小值情况,因为最小值可能因为乘以一个负数成为最大值.
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//动态规划
int maxProduct(int A[], int n) {
	vector<int>p(n, 0);
	vector<vector<int> >Path(n, p);
	int Maxdata = INT_MIN;
	for (int i = 0; i != n; ++i){
		Path[i][i] = A[i];
		if (Path[i][i] > Maxdata)
			Maxdata = Path[i][i];
	}
	for (int i = 0; i != n - 1; ++i){
		for (int j = i + 1; j != n; ++j){
			Path[i][j] = Path[i][j - 1] * A[j];
			if (Path[i][j] > Maxdata)
				Maxdata = Path[i][j];
		}
	}
	return Maxdata;
}
//记录最大最小值
int maxProduct(int A[], int n) {
	int Curmax = 1;
	int Curmin = 1;
	int ResultMax = INT_MIN;
	for (int i = 0; i != n;++i)
	{
		int Curtmp = Curmax*A[i];
		Curmax = max(Curtmp, max(A[i], Curmin*A[i]));
		Curmin = min(Curtmp, min(A[i], Curmin*A[i]));
		ResultMax = Curmax > ResultMax ? Curmax : ResultMax;
	}
	return ResultMax;
}



Maximum Product Subarray

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/43702405

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