标签:
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
.
解题思路:
#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; }
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/43702405