Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

152. 乘积最大子数组 #43

Open
webVueBlog opened this issue Sep 12, 2022 · 0 comments
Open

152. 乘积最大子数组 #43

webVueBlog opened this issue Sep 12, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

152. 乘积最大子数组

Description

Difficulty: 中等

Related Topics: 数组, 动态规划

给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。

测试用例的答案是一个 32-位 整数。

子数组 是数组的连续子序列。

示例 1:

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

示例 2:

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

提示:

  • 1 <= nums.length <= 2 * 104
  • -10 <= nums[i] <= 10
  • nums 的任何前缀或后缀的乘积都 保证 是一个 32-位 整数

Solution

Language: JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function (nums) {
    let min = 1, max = 1, res = -Infinity
    for (let num of nums) {
        if (num < 0) [min, max] = [max, min]
        max = Math.max(num * max, num)
        min = Math.min(num * min, num)
        res = Math.max(res, max)
    }
    return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant