AlgoMaster Logo

Maximum Product Subarray

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The brute force approach is to generate all possible subarrays of the given array and calculate their products. Among all these products, we find the maximum product.

Steps:

  1. Use a nested loop to consider every subarray from i to j.
  2. For each subarray, compute the product.
  3. Track the maximum product encountered.

Code:

2. Dynamic Programming (Kadane's Algorithm)

Intuition:

The product of elements in subarrays can be disrupted by negative numbers and zeros. A negative number turns a positive product into negative and vice versa, while zero resets it. Thus, we need to track both the maximum and minimum product subarrays because a negative product might become the largest if multiplied by another negative number.

Instead of recalculating products for every possible subarray, we maintain two potential products:

  • maxProductSoFar: Maximum product subarray ending at the current position.
  • minProductSoFar: Minimum product subarray ending at the current position (to handle the case of two negative numbers resulting in a positive product).

Steps:

  1. Iterate through the array, maintaining both maxProductSoFar and minProductSoFar.
  2. If a negative number is encountered, swap maxProductSoFar and minProductSoFar.
  3. Update the maxProductSoFar and minProductSoFar at each step.
  4. Track the global maximum product.

Code: