#152

Maximum Product Subarray

Medium
ArrayDynamic ProgrammingDynamic ProgrammingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass through the array, keeping track of both the maximum and minimum products at each position. This is crucial because a negative number can turn a small product into a large one when multiplied.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize variables for max_product, min_product, and result.
  2. 2Step 2: Iterate through the array, updating max_product and min_product based on the current number.
  3. 3Step 3: Update the result with the maximum of itself and max_product.
solution.py9 lines
1def maxProduct(nums):
2    max_product = min_product = result = nums[0]
3    for num in nums[1:]:
4        if num < 0:
5            max_product, min_product = min_product, max_product
6        max_product = max(num, max_product * num)
7        min_product = min(num, min_product * num)
8        result = max(result, max_product)
9    return result

Complexity note: The time complexity is O(n) because we only go through the array once. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1The product of negative numbers can become positive, so we need to track both maximum and minimum products.
  • 2A single pass through the array is sufficient to find the maximum product subarray.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.