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.
暴力错误解法1:(没考虑 -2 3 4 -4 的这类情况,不连续的负负为正)
using namespace std;
class Solution {
public:
int maxProduct(vector<int>& nums) {
if(nums.size() <= 0)
return 0;
if(nums.size() == 1)
return nums[0];
int product = 1;
int max = 0;
int temp;
for(int i = 0; i < nums.size(); i++) {
temp = product;
product *= nums[i];
if(temp > product) {
if( max < temp )
max = temp;
product = nums[i];
if( max < product) {
max = product;
}
}
else {
if(temp == product) {
if( max < temp )
max = temp;
product = nums[i];
}
else {
if(temp < product) {
if( max < product )
max = product;
}
}
}
}
return max;
}
};
int main() {
vector<int> nums;
nums.push_back(-2);
Solution s;
cout << s.maxProduct(nums) << endl;
}暴力错误解法2:(不连续)
class Solution {
public:
int maxProduct(vector<int>& nums) {
if(nums.size() == 1)
return nums[0];
int sup = 1;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != 0)
sup *= nums[i];
}
int result;
int m = sup;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != 0) {
result = sup / nums[i];
if( m < result) {
m = result;
}
}
}
return m;
}
};简单想了一下,这类解法不可以,还是需要 dynamic Programming,稍后补上 AC 的代码。
本文探讨了如何找到数组中具有最大乘积的连续子数组,并提供了两种错误的解法及其分析,旨在理解并解决负数乘积带来的挑战。

1623

被折叠的 条评论
为什么被折叠?



