KatInterview

152. Maximum Product Subarray

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the maximum product of a contiguous subarray within a given array of integers. The key challenge lies in handling negative numbers and zeroes.

Solution

Maximum Product Subarray in Python

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        # Constraints: len(nums) >= 1, so no empty check needed.

        # Initialize max/min product ending at the first element.
        max_so_far = nums[0]
        min_so_far = nums[0]
        result = nums[0]

        # Iterate through the array starting from the second element.
        for i in range(1, len(nums)):
            num = nums[i]

            # Store the previous max_so_far. It's needed for calculating the new min_so_far,
            # as max_so_far itself will be updated first.
            # In Python, we can compute both new values before assignment to avoid a temp variable.
            candidates = (num, num * max_so_far, num * min_so_far)
            
            max_so_far = max(candidates)
            min_so_far = min(candidates)

            # Update the overall maximum product found so far.
            result = max(result, max_so_far)

        return result

Maximum Product Subarray in Java

class Solution {
    public int maxProduct(int[] nums) {
        // Constraints: nums.length >= 1, so no empty check needed.

        // Initialize max/min product ending at the first element.
        int maxSoFar = nums[0];
        int minSoFar = nums[0];
        int result = nums[0];

        // Iterate through the array starting from the second element.
        for (int i = 1; i < nums.length; i++) {
            int num = nums[i];

            // Store the previous max_so_far. It's needed for calculating the new min_so_far,
            // as max_so_far itself will be updated first.
            int prevMax = maxSoFar;

            // The new max product ending at i can be:
            // 1. num itself (starting a new subarray).
            // 2. num * prevMax (extending with a positive product).
            // 3. num * minSoFar (extending with a negative product, which might become positive).
            maxSoFar = Math.max(num, Math.max(num * prevMax, num * minSoFar));

            // Similarly for the new min product.
            minSoFar = Math.min(num, Math.min(num * prevMax, num * minSoFar));

            // Update the overall maximum product found so far.
            result = Math.max(result, maxSoFar);
        }

        return result;
    }
}

Maximum Product Subarray in C++

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        // Constraints: nums.length >= 1, so no empty check needed.
        
        // Initialize max/min product ending at the first element.
        int max_so_far = nums[0];
        int min_so_far = nums[0];
        int result = nums[0];
        
        // Iterate through the array starting from the second element.
        for (int i = 1; i < nums.size(); i++) {
            int num = nums[i];
            
            // Store the previous max_so_far. It's needed for calculating the new min_so_far,
            // as max_so_far itself will be updated first.
            int prev_max = max_so_far;
            
            // The new max product ending at i can be:
            // 1. num itself (starting a new subarray).
            // 2. num * prev_max (extending with a positive product).
            // 3. num * min_so_far (extending with a negative product, which might become positive).
            max_so_far = max({num, num * prev_max, num * min_so_far});
            
            // Similarly for the new min product.
            min_so_far = min({num, num * prev_max, num * min_so_far});
            
            // Update the overall maximum product found so far.
            result = max(result, max_so_far);
        }
        
        return result;
    }
};

Maximum Product Subarray in TypeScript

function maxProduct(nums: number[]): number {
    // Constraints: nums.length >= 1, so no empty check needed.

    // Initialize max/min product ending at the first element.
    let maxSoFar: number = nums[0];
    let minSoFar: number = nums[0];
    let result: number = nums[0];

    // Iterate through the array starting from the second element.
    for (let i = 1; i < nums.length; i++) {
        const num = nums[i];

        // Store the previous max_so_far. It's needed for calculating the new min_so_far,
        // as max_so_far itself will be updated first.
        const prevMax = maxSoFar;

        // The new max product ending at i can be:
        // 1. num itself (starting a new subarray).
        // 2. num * prevMax (extending with a positive product).
        // 3. num * minSoFar (extending with a negative product, which might become positive).
        maxSoFar = Math.max(num, num * prevMax, num * minSoFar);

        // Similarly for the new min product.
        minSoFar = Math.min(num, num * prevMax, num * minSoFar);

        // Update the overall maximum product found so far.
        result = Math.max(result, maxSoFar);
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.