题目意思: 给定一个数组,求最大连续子序列的乘积
分析: 简单dp。maxDp[i]表示以num[i]结尾的最大子序列乘积,minDp[i]类似
maxDp[i] = max{num[i], maxDp[i-1]*num[i], minDp[i-1]*num[i]}
minDp[i] = min{num[i], minDp[i-1]*num[i], maxDp[i-1]*num[i]}
之所以要minDp,是因为有负数的存在,导致多了一个状态。
代码:
class Solution { public: int maxProduct(int A[], int n); }; int Solution::maxProduct(int A[], int n) { int* minDp = new int[n]; int* maxDp = new int[n]; minDp[0] = maxDp[0] = A[0]; int res = maxDp[0]; for(int i = 1; i < n; i++){ minDp[i] = min(min(minDp[i-1]*A[i], A[i]), maxDp[i-1]*A[i]); maxDp[i] = max(max(maxDp[i-1]*A[i], A[i]), minDp[i-1]*A[i]); res = max(res, maxDp[i]); } delete minDp; delete maxDp; minDp = maxDp = NULL; return res; }