[leetcode]152. Maximum Product Subarray

原创 2016年08月28日 15:58:00
//由于负数*负数的结果可能比原值还大,所以要记录一个max还要记录一个min
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int n=nums.size();
        if(n<1)
            return 0;
        if(n==1)
            return nums[0];
            
        int minLast=nums[0];
        int maxLast=nums[0];
        int minCur;
        int maxCur;
        int product=nums[0];
        
        for(int i=1;i<n;i++)
        {
            maxCur=max(nums[i],max(maxLast*nums[i],minLast*nums[i]));
            minCur=min(nums[i],min(maxLast*nums[i],minLast*nums[i]));
            
            maxLast=maxCur;
            minLast=minCur;
            
            product=max(product,maxCur);
        }
        return product;
        
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Leetcode 152 Maximum Product Subarray 子数组最大乘积

在数组(至少包含一个元素)中找到一个连续的子数组,使得该子数组元素的乘积最大。...

leetcode(152). Maximum Product Subarray

problem Find the contiguous subarray within an array (containing at least one number) which has...

[leetcode] 152.Maximum Product Subarray

题目: Find the contiguous subarray within an array (containing at least one number) which has the lar...

leetcode 152. Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest ...

Leetcode152——Maximum Product Subarray

Leetcode152——Maximum Product Subarray

Leetcode 152. Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest ...

leetcode - 152. Maximum Product Subarray

算法系列博客之Dynamic Programming 本篇博客将运用动态规划的思想来解决leetcode上198和213号问题 问题描述:Find the contiguous subarray ...
  • Quiteen
  • Quiteen
  • 2017年06月11日 16:05
  • 94

【LeetCode-面试算法经典-Java实现】【152-Maximum Product Subarray(子数组的最大乘积)】

【152-Maximum Product Subarray(子数组的最大乘积)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】代码下载【https://github.com/Wa...

Leetcode(152) Maximum Product Subarray

题目如下: Find the contiguous subarray within an array (containing at least one number) which has the...

[leetcode] 152 Maximum Product Subarray

先来一个比较简单的题目,也是出现较多的,求连续的最大子数组和,见hdu 1003. 比较简单的动态规划,如果当前的连续和小于0时,再加则一定会小于nums[i]的当前值,此时应该取nums[i]. ...
  • NK_test
  • NK_test
  • 2015年09月22日 23:54
  • 2638
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[leetcode]152. Maximum Product Subarray
举报原因:
原因补充:

(最多只允许输入30个字)