乘积的最大子序列

题目描述:

给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。

示例 1: 输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。

示例 2: 输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray

解题方案:

思路

  • 标签:动态规划 遍历数组时计算当前最大值,不断更新
  • 令currMax为当前最大值,则当前最大值为 currMax = Math.max(n ,Math.max(m,x));
  • 由于存在负数,那么会导致最大的变最小的,最小的变最大的。因此还需要维护当前最小值currMin,currMin = Math.min(n,Math.min(m,x));
  • 时间复杂度:O(n)

代码

java版本

class Solution {
    public int maxProduct(int[] nums) {
    int len = nums.length;
    if(len == 0)
        return 0;
    int res=nums[0], currMax = nums[0], currMin = nums[0],max,min;

    for(int i = 1; i < len; i++) {
        int x = nums[i];  //x赋值只是便于下面书写
        //max,min解决了x为正负两种情况的最大值
        max = currMax * x;   
        min = currMin * x;
        currMax = Math.max(max ,Math.max(min,x));
        currMin = Math.min(max,Math.min(min,x));
        
        res = Math.max(currMax,res);
    }
    return res;
    }
}

c++版本

#include<cstdio>
#include<iostream>
#include<vector>

using namespace std;

int maxProduct(vector<int>& nums) {
    int len = nums.size();
    if(len == 0)
        return 0;
    int res=nums[0], currMax = nums[0], currMin = nums[0],max,min;

    for(int i = 1; i < len; i++) {
        int x = nums[i];
        max = currMax * x;
        min = currMin * x;
        currMax = max(max ,max(min,x));
        currMin = min(max,min(min,x));
        //cout << currMax << "   "  << currMin << endl;
        res = max(currMax,res);
    }
    return res;
}

int main()
{
    vector<int> a;
    a.push_back(-1);
    a.push_back(-2);
    a.push_back(-9);
    a.push_back(-6);
    cout << maxProduct(a) << endl;
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值