152. Maximum Product SubarrayMedium16.4K503Companies
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Input: nums = [-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 max = nums[0];
let minMax = nums[0];
let maxMax = nums[0];
for (let i = 1; i < nums.length; i++) {
const curr = nums[i];
if (curr < 0) {
const temp = minMax;
minMax = maxMax;
maxMax = temp;
}
minMax = Math.min(curr, minMax * curr);
maxMax = Math.max(curr, maxMax * curr);
max = Math.max(maxMax, max);
}
return max;
};
/**
* @param {number[]} nums
* @return {number}
*/
let max;
var maxProduct = function(nums) {
max = {};
calcLocal(nums, 0, nums.length - 1);
return max.val;
};
function calcLocal(nums, lo, hi) {
if (lo === hi) {
return nums[lo];
}
const m = lo + Math.floor((hi - lo) / 2);
const left = calcLocal(nums, lo, m); // { left, right, total}
const right = calcLocal(nums, m + 1, hi); // { left, right, total}
const product = calcProduct();
// left.right * right.left, total * total
return { left, right, total}
}