标签:leetcode
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.
这一题一开始不知道dp公式怎么写。试一试暴力,结果果然不行。
TLE代码如下
class Solution {
public:
int maxProduct(vector<int>& nums) {
if(nums.size()==0) return 0;
int m = nums.size();
int res = 1;
for(int i=0;i<m;i++){
int tmp = 1;
for(int j=i;j<m;j++){
tmp *= nums[j];
if(tmp>res) res=tmp;
}
}
return res;
}
};
正确的情况要记录下当前的最大值以及最小值,才能得出最后的值。
class Solution {
public:
vector<int> ans;
int maxProduct(vector<int>& nums) {
if(nums.size()==0) return 0;
int m = nums.size();
int res = 1;
int locmin = nums[0],locmax = nums[0],global =nums[0];
for(int i=1;i<m;i++){
int tmp = locmax; locmax=max(max(nums[i]*locmax,nums[i]),nums[i]*locmin);
locmin=min(min(nums[i]*tmp,nums[i]),nums[i]*locmin);
global=max(global,locmax);
}
return global;
}
};
[leetcode]Maximum Product Subarray
标签:leetcode
原文地址:http://blog.csdn.net/iboxty/article/details/45100545