Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

152. Maximum Product Subarray

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.

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.