Maximum Product Subarray

来源:互联网 发布:免费量化交易软件 编辑:程序博客网 时间:2024/05/29 08:32

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;}



0 0
原创粉丝点击