152. Maximum Product Subarray(js)
152. Maximum Product Subarray
Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
题意:给定一个数字数组(包含正数,负数和零),求连续子数组项的乘积的最大值
代码如下:
/** * @param {number[]} nums * @return {number} */ var maxProduct = function(nums) { let mx=nums[0]; let mn=nums[0]; let res=nums[0]; for(let i=1;i<nums.length;i++){ // max:数组前i+1项的最大乘积 // min:数组前i+1项的最小乘积 // dp思想,不断比较之前数组项的最小值*当前项,当前项,之前数组项的最大值*当前项,并不断更新最大值 let max=mx,min=mn; mx=Math.max(Math.max(min*nums[i],nums[i]),max*nums[i]); mn=Math.min(Math.min(max*nums[i],nums[i]),min*nums[i]); res=Math.max(res,mx); } return res; };