1. Understand the Goal: The user wants a program to find the "maximum product subarray". This is a classic algorithmic problem (often found on LeetCode, GeeksForGeeks, etc.).
Analyze the Problem:
Input: An array of numbers (integers, potentially including negatives and zeros).
Output: The maximum product obtainable from a contiguous subarray.
Naive Approach: Check every subarray. Time complexity O(N2). Too slow for large inputs.
Dynamic Programming / Kadane's-like variation:
A single variable (like in Maximum Sum Subarray) isn't enough because multiplying by a negative number flips the sign. A small negative minimum can become a large positive maximum if multiplied by another negative.
Therefore, we need to track both the current maximum product ending at the current position and the current minimum product ending at the current position.
Variables:
max_so_far: The overall global maximum.
max_ending_here: The maximum product of a subarray ending at the current index.
min_ending_here: The minimum product of a subarray ending at the current index.
Logic:
At each element num:
If num is positive: max increases, min decreases (gets more negative).
If num is negative: max becomes min * num, min becomes max * num.
If num is zero: The product chain breaks. max and min become 0 (but we might start fresh from the next number, effectively resetting to 1). Actually, the formula max(num, max * num) handles zero naturally.
Refined Logic:
For each num in nums:
1. Store temp_max = max_ending_here (because max_ending_here will change, but we need the old value to calculate min_ending_here).
2. max_ending_here = max(num, max(temp_max * num, min_ending_here * num))
3. min_ending_here = min(num, min(temp_max * num, min_ending_here * num))
4. max_so_far = max(max_so_far, max_ending_here)
Select Programming Language: Python is generally the most accessible and readable for algorithmic explanations. I should probably provide a C++ or Java version too, or just stick to Python as the primary, maybe offering others if requested. Let's stick to Python as the default but structure the answer well.
Drafting the Code (Python):
python
def max_product_subarray(nums):
if not nums:
return 0
# Initialize max_so_far to the first element (handles arrays of length 1)
max_so_far = nums[0]
max_ending_here = nums[0]
min_ending_here = nums[0]
# Loop from the second element
for i in range(1, len(nums)):
num = nums[i]
# If current number is negative, swapping max and min is a common optimization,
# or just calculate both before assignment.
# Let's use the calculation approach for clarity.
temp_max = max_ending_here
max_ending_here = max(num, max(temp_max * num, min_ending_here * num))
min_ending_here = min(num, min(temp_max * num, min_ending_here * num))
# Update global max
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
Edge Cases:
Empty array: Return 0 or throw exception. (Code checks if not nums).
Array with 0s: Handled by max(num, ...) logic. If num is 0, max_ending_here becomes 0. The next iteration (if num is not 0) will pick max(num, ...) effectively restarting the subarray.
All negatives: Works as expected.
Single element: Loop doesn't run, returns nums[0]. Correct.
Why this works: A disruption (zero) splits the array. A single negative number flips the sign. If there is an odd number of negatives, one will be left out. Traversing both directions ensures we catch the subarray that excludes that one specific negative number on the edge.
Decision: The Dynamic Programming approach (Max/Min tracking) is O(N) time and O(1) space, and is the standard "interview" answer. I will provide this one as the primary solution.
This problem is trickier than the "Maximum Sum Subarray" because multiplying two negative numbers creates a large positive number. Therefore, we must track both the maximum product (in case the next number is positive) and the minimum product (in case the next number is negative) at every step.
The Algorithm
We iterate through the array once (O(N) time complexity). At each number, we calculate three values:
The current number itself (starting a new subarray).
The current number multiplied by the previous maximum product (extending the positive chain).
The current number multiplied by the previous minimum product (turning a negative chain positive).
The largest of these three becomes the new maximum product. The smallest becomes the new minimum product.
Python Implementation
python
def max_product_subarray(nums):
# Handle edge case for empty array
if not nums:
return 0
# Initialize variables based on the first element
# We use the first element because the max product could be the first number itself
current_max = nums[0]
current_min = nums[0]
global_max = nums[0]
# Iterate starting from the second element
for i in range(1, len(nums)):
num = nums[i]
# If the current number is negative, swapping max and min is a shortcut.
# Why? Because neg * large_pos becomes large_neg, and neg * large_neg becomes large_pos.
if num < 0:
current_max, current_min = current_min, current_max
# Calculate new potential max and min
# Option 1: Start fresh from current number (num)
# Option 2: Extend the previous subarray (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 ---
test_cases = [
[2, 3, -2, 4], # Expected: 6 (from [2, 3])
[-2, 0, -1], # Expected: 0 (from [0])
[-2, -3, 0, -2, -40], # Expected: 80 (from [-2, -40])
[0.5, 0.1, -10] # Expected: 1 (from [0.5, 0.1, -10] is -0.5, [0.5] is 0.5, etc)
]
for nums in test_cases:
print(f"Array: {nums}\nMax Product: {max_product_subarray(nums)}\n")
Complexity Analysis
Time Complexity:O(N), where N is the number of elements. We traverse the array exactly once.
Space Complexity:O(1), as we only use three variables (current_max, current_min, global_max) regardless of the array size.
C++ Implementation
If you need a version in C++, here is the equivalent logic:
cpp
#include <iostream>
#include <vector>
#include <algorithm>
int maxProductSubarray(std::vector<int>& nums) {
if (nums.empty()) return 0;
int current_max = nums[0];
int current_min = nums[0];
int global_max = nums[0];
for (size_t i = 1; i < nums.size(); ++i) {
int num = nums[i];
// If current number is negative, swap max and min
if (num < 0) {
std::swap(current_max, current_min);
}
current_max = std::max(num, current_max * num);
current_min = std::min(num, current_min * num);
global_max = std::max(global_max, current_max);
}
return global_max;
}
Final Code Structure:
Language: Python.
Time Complexity: O(N).
Space Complexity: O(1).
Writing the Response:
(Self-Correction during drafting): Make sure to explicitly mention that we need to store max_ending_here in a temporary variable before updating it, because we need the old value to calculate the new min_ending_here.