Given an integer array nums
, find a subarray that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Explanation:
Given an array nums of integers, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Solution
We can keep track of the maximum and minimum product at each index i. Then, at each index i, we update the maximum and minimum product by taking the maximum and minimum of the previous maximum and minimum, and the current element. The maximum product will be the maximum of the current maximum and minimum products.
Code in JavaScript:
var maxProduct = function(nums) { if (nums.length === 0) return 0; let max = nums[0]; let min = nums[0]; let res = nums[0]; for (let i = 1; i < nums.length; i++) { let currMax = Math.max(max * nums[i], min * nums[i], nums[i]); let currMin = Math.min(max * nums[i], min * nums[i], nums[i]); res = Math.max(res, currMax); max = currMax; min = currMin; } return res; };
Essentially what we do is keep track of the maximum and minimum product at each index i. Then, at each index i, we update the maximum and minimum product by taking the maximum and minimum of the previous maximum and minimum, and the current element. The maximum product will be the maximum of the current maximum and minimum products.