Arrays Linked Lists Questions Medium
To find the maximum product subarray in an array, we can use a dynamic programming approach.
First, we initialize two variables, max_product and min_product, both set to the first element of the array. These variables will keep track of the maximum and minimum product subarrays ending at the current element.
Then, we iterate through the array starting from the second element. For each element, we update the max_product and min_product variables based on three possibilities:
1. If the current element is positive, we multiply it with the max_product and min_product variables. The max_product will be updated with the maximum of the current element or the product of the current element and the max_product, while the min_product will be updated with the minimum of the current element or the product of the current element and the min_product.
2. If the current element is zero, we reset both max_product and min_product to 1, as any subarray with zero will have a product of zero.
3. If the current element is negative, we swap the max_product and min_product variables before updating them as described in the first possibility. This is because multiplying a negative number with the minimum product will result in a maximum product.
During each iteration, we also keep track of the maximum product found so far in a separate variable, max_product_so_far.
Finally, after iterating through the entire array, the max_product_so_far will contain the maximum product subarray.
Here is the implementation in Python:
def find_max_product_subarray(arr):
max_product = arr[0]
min_product = arr[0]
max_product_so_far = arr[0]
for i in range(1, len(arr)):
if arr[i] > 0:
max_product = max(arr[i], max_product * arr[i])
min_product = min(arr[i], min_product * arr[i])
elif arr[i] == 0:
max_product = 1
min_product = 1
else:
temp = max_product
max_product = max(arr[i], min_product * arr[i])
min_product = min(arr[i], temp * arr[i])
max_product_so_far = max(max_product_so_far, max_product)
return max_product_so_far
# Example usage
arr = [2, 3, -2, 4]
max_product_subarray = find_max_product_subarray(arr)
print(max_product_subarray)
Output:
6
In the given example, the maximum product subarray is [2, 3], which gives a product of 6.