Solving Leetcode 152. Maximum Product Subarray

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.

Related

How to 10x Your LLM Prompting With DSPy

Tired of spending countless hours tweaking prompts for large...

Google Announces A Cost Effective Gemini Flash

At Google's I/O event, the company unveiled Gemini Flash,...

WordPress vs Strapi: Choosing the Right CMS for Your Needs

With the growing popularity of headless CMS solutions, developers...

JPA vs. JDBC: Comparing the two DB APIs

Introduction The eternal battle rages on between two warring database...

Meta Introduces V-JEPA

The V-JEPA model, proposed by Yann LeCun, is a...

Subscribe to our AI newsletter. Get the latest on news, models, open source and trends.
Don't worry, we won't spam. 😎

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Lusera will use the information you provide on this form to be in touch with you and to provide updates and marketing.