Skip to content

Latest commit

 

History

History
26 lines (20 loc) · 726 Bytes

0152. 乘积最大子数组.md

File metadata and controls

26 lines (20 loc) · 726 Bytes

152. 乘积最大子数组

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

https://leetcode-cn.com/problems/maximum-product-subarray/


/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
  var min = max = result = nums[0]
  for (var i = 1; i < nums.length; i ++) {

    var minTemp = min, maxTemp = max

    min = Math.min(nums[i] * maxTemp, nums[i], nums[i] * minTemp)
    max = Math.max(nums[i] * minTemp, nums[i], nums[i] * maxTemp)
    result = Math.max(result, max) // 及时把 max 存下来,避免被 0 截断
  }
  return result
};