[leetcode]Maximum Product Subarray

来源:互联网 发布:淘宝销售额排行榜 编辑:程序博客网 时间:2024/06/06 04:58

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;    }};
0 0
原创粉丝点击