题目大意:求一个数组中最大连续子数组的乘积。
这题的第一反应是动态规划,而且经过思考之后,不可能只定义一个状态就能够解决这个问题,必须得定义两个状态(看另一题需要定义两个状态才能求解的DP问题:https://blog.csdn.net/weixin_43462819/article/details/83240210 )
1.我的解法
我的解法是自己思考出来的,但是过程很繁琐。定义两个数组:dp1和dp2,其中:
dp1[i]:代表以数组中第i个数结尾的连续子数组的最大乘积
dp2[i]:代表以数组中第i个数结尾的连续子数组的最小乘积
具体的状态转移方程就不列出来了,非常繁琐,而且看代码而且也能看明白。
在列转移方程时,需要记住的是,对于任意的k(在范围内),dp1[k] >= dp2[k]
代码:
class Solution {
public:
int maxProduct(vector<int>& nums) {
int sz = nums.size();
if (sz == 0)
return 0;
vector<int> dp1(sz), dp2(sz);
dp1[0] = dp2[0] = nums[0];
for (int i = 1; i < sz; ++i) {
if (nums[i] > 0) {
if (dp1[i-1] < 0)
dp1[i] = nums[i];
else if (dp1[i-1] > 0)
dp1[i] = nums[i] * dp1[i-1];
else dp1[i] = nums[i];
if (dp2[i-1] < 0)
dp2[i] = nums[i] * dp2[i-1];
else if (dp2[i-1] > 0)
dp2[i] = nums[i];
else dp2[i] = 0;
}
else if (nums[i] < 0) {
if (dp2[i-1] < 0)
dp1[i] = nums[i] * dp2[i-1];
else if (dp2[i-1] > 0)
dp1[i] = nums[i];
else dp1[i] = 0;
if (dp2[i-1] < 0) {
if (dp1[i-1] > 0)
dp2[i] = dp1[i-1] * nums[i];
else dp2[i] = nums[i];
}
else if (dp2[i-1] > 0)
dp2[i] = dp1[i-1] * nums[i];
else dp2[i] = nums[i] * (dp1[i-1] > 0? dp1[i-1] : 1);
}
else {
dp1[i] = 0;
dp2[i] = 0;
}
}
for (auto &item : dp1)
cout << item << " ";
cout << endl;
for (auto &item : dp2)
cout << item << " ";
cout << endl;
return *max_element(dp1.begin(), dp1.end());
}
};
确实很复杂
2.一个巧妙的解法
这是我从评论区看来的。差点把我看哭了。
直接先看代码:
int maxProduct(int A[], int n) {
// store the result that is the max we have found so far
int r = A[0];
// imax/imin stores the max/min product of
// subarray that ends with the current number A[i]
for (int i = 1, imax = r, imin = r; i < n; i++) {
// multiplied by a negative makes big number smaller, small number bigger
// so we redefine the extremums by swapping them
if (A[i] < 0)
swap(imax, imin);
// max/min product for the current number is either the current number itself
// or the max/min by the previous number times the current one
imax = max(A[i], imax * A[i]);
imin = min(A[i], imin * A[i]);
// the newly computed max value is a candidate for our global result
r = max(r, imax);
}
return r;
}
给我的教训有两点:
1.当使用DP时,如果每次都只用到前面的一个状态,那么不用把所有DP全部存储起来,只需要使用一个变量来存储就可以了。而且如果最终的答案不在最后的位置,那么需要一个额外的变量在每次的迭代中与这次迭代的结果相比较。
2.善用max,min。不是指这两个函数,而是指善用这两个概念,可以避免许多不必要的“斤斤计较”的计算,比如我自己的解法的分析太细致了,但是min,max可以快刀斩乱麻。