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. Maximum Product Subarray #166

Open
Tcdian opened this issue May 18, 2020 · 1 comment
Open

152. Maximum Product Subarray #166

Tcdian opened this issue May 18, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 18, 2020

152. Maximum Product Subarray

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

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.
@Tcdian
Copy link
Owner Author

Tcdian commented May 18, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
    let result = -Infinity;
    let maxProduct = 1;
    let minProduct = 1;
    for(let i = 0; i < nums.length; i++) {
        let prevMaxProduct = maxProduct;
        let prevMinProduct = minProduct;
        maxProduct = Math.max(prevMaxProduct * nums[i], prevMinProduct * nums[i], nums[i]);
        minProduct = Math.min(prevMaxProduct * nums[i], prevMinProduct * nums[i], nums[i]);
        result = Math.max(maxProduct, result);
    }
    return result;
};

@Tcdian Tcdian added the Classic label May 23, 2020
@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant