Leetcode NO.152 Maximum Product Subarray

本题题目要求如下:

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模型,虽然思路大致正确,也解出了结果,而且运行结果不错,但是代码不够简练。。

现在介绍下本题的做法。。。

本题设定两个vector,一个存储以该点为终点的最小值(绝对值最大的负值),另外一个存储以该点为终点的最大值。。

比如本题的例子[2,3,-2,4]

运行结果如下:

  • 初始化:pos[0,0,0,0], neg[0,0,0,0]
  • 对2处理: pos[2,0,0,0], neg[0,0,0,0]
  • 对3处理: pos[2,6,0,0], neg[0,0,0,0] // 2 * 3 = 6
  • 对-2处理: pos[2,6,0,0], neg[0,0,-12,0] // 6 * -2 = -12
  • 对4处理: pos[2,6,0,0], neg[0,0,-12,-24]
公式如下:

pos[i] = max(pos[i-1]*num[i], neg[i-1]*num[i], num[i])

neg[i] = min(pos[i-1]*num[i], neg[i-1]*num[i], num[i])

代码如下:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        vector<int> pos(nums.size(), 0);
        vector<int> neg(nums.size(), 0);
        if (nums[0] > 0) {
        	pos[0] = nums[0];
        }
        else {
        	neg[0] = nums[0];
        }
        int max_item = nums[0];
        for (int i = 1; i < nums.size(); ++i) {
        	pos[i] = max(pos[i-1]*nums[i], max(nums[i], neg[i-1]*nums[i]));
        	neg[i] = min(pos[i-1]*nums[i], min(nums[i], neg[i-1]*nums[i]));
        	if (pos[i] > max_item)
        		max_item = pos[i];
        }
        return max_item;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值