LeetCode 152: Maximum Product Subarray Solution

Master LeetCode problem 152 (Maximum Product Subarray), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

152. Maximum Product Subarray

Problem Explanation

Explanation:

To solve this problem, we can use a dynamic programming approach. We will keep track of both the maximum and minimum products ending at each position in the array. This is because a negative number multiplied by a negative number can become a positive number, so we need to keep track of both the maximum and minimum products.

At each position, we update the maximum and minimum products by considering three possibilities:

  1. Current element is positive: we multiply it with the maximum product ending at the previous position.
  2. Current element is negative: we multiply it with the minimum product ending at the previous position.
  3. Current element resets the subarray: we start a new subarray from the current element.

Finally, we return the maximum product encountered during these iterations.

Solution Code

class Solution {
    public int maxProduct(int[] nums) {
        int maxProd = nums[0];
        int minProd = nums[0];
        int result = nums[0];
        
        for (int i = 1; i < nums.length; i++) {
            int temp = maxProd;
            maxProd = Math.max(nums[i], Math.max(maxProd * nums[i], minProd * nums[i]));
            minProd = Math.min(nums[i], Math.min(temp * nums[i], minProd * nums[i]));
            result = Math.max(result, maxProd);
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 152 (Maximum Product Subarray)?

This page provides optimized solutions for LeetCode problem 152 (Maximum Product Subarray) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 152 (Maximum Product Subarray)?

The time complexity for LeetCode 152 (Maximum Product Subarray) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 152 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 152 in Java, C++, or Python.

Back to LeetCode Solutions