首页 > 其他 > 详细

[leetcode]Maximum Product Subarray

时间:2015-04-17 22:22:21      阅读:153      评论:0      收藏:0      [点我收藏+]

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

原文:http://blog.csdn.net/iboxty/article/details/45100545

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!