1. Understand the Goal: The user wants a program to find the "maximum product subarray".
-
Analyze the Problem:
- Input: An array of integers (e.g.,
[2, 3, -2, 4]).
- Output: The maximum product of a contiguous subarray (e.g., for
[2, 3, -2, 4], the subarray [2, 3] has product 6, which is the max).
- Edge Cases:
- Zeros: Reset the product.
- Negative numbers: Two negatives make a positive. This is the tricky part. If we only keep track of the maximum so far, a large negative number might become the new maximum if multiplied by another negative.
- Examples:
[2, 3, -2, 4] -> 2 * 3 = 6.
[-2, 0, -1] -> 0.
[-2, 3, -4] -> (-2) * 3 * (-4) = 24.
-
Determine the Algorithm:
- Naive Approach: Two loops, calculate product for every subarray. Time complexity: O(n2). Not ideal.
- Dynamic Programming / Optimized Approach:
- We need to track the maximum product ending at the current position (
max_so_far).
- Crucially, because of negative numbers, we also need to track the minimum product ending at the current position (
min_so_far). Why? Because if the current number is negative, multiplying it by the minimum (most negative) product gives the maximum (positive) product.
- Let
arr be the input array.
- Initialize
max_so_far = arr[0], min_so_far = arr[0], result = arr[0].
- Iterate from
i = 1 to n-1:
- Current element is
curr = arr[i].
- If
curr is negative, swap max_so_far and min_so_far. (Intuition: multiplying by negative flips the scale).
- Update
max_so_far = max(curr, max_so_far * curr).
- Update
min_so_far = min(curr, min_so_far * curr).
- Update
result = max(result, max_so_far).
- Time Complexity: O(n).
- Space Complexity: O(1).
-
Select Programming Language: Python is generally the most readable and requested for algorithmic problems, but providing a C++ or Java option is good practice. I will stick to Python for the primary explanation but might mention it's Python.
-
Drafting the Code (Python):
def max_product_subarray(nums):
if not nums:
return 0
# Initialize max_prod, min_prod, and result with the first element
max_prod = nums[0]
min_prod = nums[0]
result = nums[0]
# Iterate through the array starting from the second element
for i in range(1, len(nums)):
num = nums[i]
# If current number is negative, swapping max and min
# is crucial because a negative * negative becomes positive (large)
if num < 0:
max_prod, min_prod = min_prod, max_prod
# Calculate new max and min
# max_prod is either the current number itself (starting a new subarray)
# or the product of the previous max and current number
max_prod = max(num, max_prod * num)
# min_prod is either the current number itself
# or the product of the previous min and current number
min_prod = min(num, min_prod * num)
# Update the global result
result = max(result, max_prod)
return result
-
Refining the Explanation:
- Start with the logic explanation. Why is this O(n)?
- Explain the "two variables" strategy (tracking min and max).
- Provide the code.
- Provide test cases to verify understanding.
-
Review against constraints/issues:
- Does it handle zeros? Yes,
max(num, ...) resets the product to 0, and subsequent logic handles it.
- Does it handle single element arrays? Yes, loop range
1 to len handles it correctly (returns nums[0]).
- Does it handle all negatives? e.g.,
[-2, -3, -1].
- i=0: max=-2, min=-2, res=-2
- i=1 (-3): num<0 swap. max=-2, min=-2.
- Wait, let's trace manually.
max_prod = max(-3, -2*-3) = 6. min_prod = min(-3, -2*-3) = 6. Wait, min should be tracking the lowest.
- Correction: After swap:
temp_max = max(num, old_min * num)
temp_min = min(num, old_max * num)
- Actually, the code logic:
if num < 0: swap(max, min)
max = max(num, max * num) -> Here max is the old min (due to swap).
min = min(num, min * num) -> Here min is the old max (due to swap).
- Trace
[-2, -3]:
- Start: max=-2, min=-2, res=-2.
- i=1 (-3): num < 0. Swap. max=-2, min=-2.
- New max:
max(-3, -2 * -3) = max(-3, 6) = 6.
- New min:
min(-3, -2 * -3) -> Wait, min was old_max (-2). So min(-3, -2 * -3) = 6. This is wrong. The min should be .
The tricky part of this problem is handling negative numbers. A negative number can turn a minimum product (very negative) into a maximum product (very positive) if multiplied by another negative number. Therefore, we must track both the maximum and minimum product at every step.
Python Solution
def max_product_subarray(nums):
# Handle edge case for empty array
if not nums:
return 0
# Initialize max_product and min_product to the first element.
# We use the first element because the subarray must be non-empty.
current_max = nums[0]
current_min = nums[0]
global_max = nums[0]
# Iterate through the rest of the array
for i in range(1, len(nums)):
num = nums[i]
# If the current number is negative, swapping the current max and min
# is necessary. Why?
# Because: negative * minimum = maximum
# And: negative * maximum = minimum
if num < 0:
current_max, current_min = current_min, current_max
# Calculate the new max and min.
# We either start a new subarray at 'num', or extend the previous subarray.
# Example for max: max(num, current_max * num)
current_max = max(num, current_max * num)
current_min = min(num, current_min * num)
# Update the global maximum found so far
global_max = max(global_max, current_max)
return global_max
# --- Test Cases ---
if __name__ == "__main__":
example1 = [2, 3, -2, 4]
print(f"Input: {example1}")
print(f"Output: {max_product_subarray(example1)}") # Expected: 6 (2*3)
example2 = [-2, 0, -1]
print(f"Input: {example2}")
print(f"Output: {max_product_subarray(example2)}") # Expected: 0
example3 = [-2, 3, -4]
print(f"Input: {example3}")
print(f"Output: {max_product_subarray(example3)}") # Expected: 24 (-2 * 3 * -4)
Explanation of the Logic
-
Variables:
current_max: The maximum product of the subarray ending at the current position.
current_min: The minimum product of the subarray ending at the current position (kept because it might become the max if multiplied by a negative number).
global_max: The overall maximum product found so far anywhere in the array.
-
The Swap Logic:
- When we encounter a negative number (
num < 0), the roles of current_max and current_min flip. A large positive number becomes a large negative number, and a large negative number becomes a large positive number.
-
The Decision (DP Step):
max(num, current_max * num): This decides whether we should extend the existing subarray (* num) or start a fresh subarray from the current number. This handles cases where previous numbers were zeros or resulted in a product smaller than the number itself.
Complexity Analysis
- Time Complexity: O(N), where N is the number of elements in the array. We only pass through the array once.
- Space Complexity: O(1), as we only use three variables for storage, regardless of the input size.