HomeLeetcode152. Maximum Product Subarray - Leetcode Solutions

152. Maximum Product Subarray – Leetcode Solutions

Description

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.

Examples:

Example 1:

Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

Solution in Python

Python
from typing import List

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        if not nums:
            return 0
        
        # Initialize the variables to store the maximum and minimum products up to the current position
        current_max = current_min = max_product = nums[0]
        
        # Iterate through the array starting from the second element
        for num in nums[1:]:
            # If the current number is negative, swapping the current max and min helps manage the sign change
            if num < 0:
                current_max, current_min = current_min, current_max
            
            # Calculate the maximum product up to the current position
            current_max = max(num, current_max * num)
            # Calculate the minimum product up to the current position
            current_min = min(num, current_min * num)
            
            # Update the global maximum product
            max_product = max(max_product, current_max)
        
        return max_product

Explanation:

  1. Initialization:
    • current_max and current_min are initialized to the first element of the array. They represent the maximum and minimum products of subarrays ending at the current position.
    • max_product is initialized to the first element, representing the maximum product found so far.
  2. Iteration:
    • We iterate through the array starting from the second element.
    • If the current number (num) is negative, we swap current_max and current_min. This is because multiplying by a negative number flips the signs, and what was previously the maximum could become the minimum and vice versa.
  3. Update current_max and current_min:
    • current_max is updated to be the maximum of the current number itself or the product of current_max and the current number.
    • current_min is updated to be the minimum of the current number itself or the product of current_min and the current number.
  4. Update max_product:
    • max_product is updated to be the maximum value between itself and current_max.
  5. Return the Result:
    • Finally, we return max_product, which holds the largest product of any subarray within the input array.

This approach ensures that we consider all possible subarrays efficiently with a time complexity of O(n).

Solution in Javascript

JavaScript
/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
    if (nums.length === 0) {
        return 0;
    }
    
    // Initialize the variables to store the maximum and minimum products up to the current position
    let currentMax = nums[0];
    let currentMin = nums[0];
    let maxProduct = nums[0];
    
    // Iterate through the array starting from the second element
    for (let i = 1; i < nums.length; i++) {
        let num = nums[i];
        
        // If the current number is negative, swapping the current max and min helps manage the sign change
        if (num < 0) {
            [currentMax, currentMin] = [currentMin, currentMax];
        }
        
        // Calculate the maximum product up to the current position
        currentMax = Math.max(num, currentMax * num);
        // Calculate the minimum product up to the current position
        currentMin = Math.min(num, currentMin * num);
        
        // Update the global maximum product
        maxProduct = Math.max(maxProduct, currentMax);
    }
    
    return maxProduct;
};

Solution in Java

Java
class Solution {
    public int maxProduct(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        
        // Initialize the variables to store the maximum and minimum products up to the current position
        int currentMax = nums[0];
        int currentMin = nums[0];
        int maxProduct = nums[0];
        
        // Iterate through the array starting from the second element
        for (int i = 1; i < nums.length; i++) {
            int num = nums[i];
            
            // If the current number is negative, swapping the current max and min helps manage the sign change
            if (num < 0) {
                int temp = currentMax;
                currentMax = currentMin;
                currentMin = temp;
            }
            
            // Calculate the maximum product up to the current position
            currentMax = Math.max(num, currentMax * num);
            // Calculate the minimum product up to the current position
            currentMin = Math.min(num, currentMin * num);
            
            // Update the global maximum product
            maxProduct = Math.max(maxProduct, currentMax);
        }
        
        return maxProduct;
    }
}

Solution in C#

C#
public class Solution {
    public int MaxProduct(int[] nums) {
        if (nums.Length == 0) {
            return 0;
        }
        
        // Initialize the variables to store the maximum and minimum products up to the current position
        int currentMax = nums[0];
        int currentMin = nums[0];
        int maxProduct = nums[0];
        
        // Iterate through the array starting from the second element
        for (int i = 1; i < nums.Length; i++) {
            int num = nums[i];
            
            // If the current number is negative, swapping the current max and min helps manage the sign change
            if (num < 0) {
                int temp = currentMax;
                currentMax = currentMin;
                currentMin = temp;
            }
            
            // Calculate the maximum product up to the current position
            currentMax = Math.Max(num, currentMax * num);
            // Calculate the minimum product up to the current position
            currentMin = Math.Min(num, currentMin * num);
            
            // Update the global maximum product
            maxProduct = Math.Max(maxProduct, currentMax);
        }
        
        return maxProduct;
    }
}

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular