Question:
Given an integer array nums
, find the contiguous subarray within the array that has the largest product, and return the product.
Example:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: The subarray [2,3] has the largest product, which is 2 * 3 = 6.
Instructions:
maxProduct(nums: List[int]) -> int
, where:
nums
: a list of integers representing the input array.nums
.Note:
Answer:
To solve this problem, we can use a dynamic programming approach. Let's follow these steps:
Initialize two variables:
max_product
to store the maximum product found so far.min_product
to store the minimum product found so far.Set the initial values of max_product
and min_product
to the first element of the input array:
max_product = nums[0]
min_product = nums[0]
Initialize a variable result
to store the final maximum product, initially set to the first element of the input array:
result = nums[0]
Iterate over the input array starting from the second element.
At each iteration, update the values of max_product
and min_product
as follows:
max_product
and min_product
of the previous subarray.max_product
to the maximum value among the current element, the previous max_product
multiplied by the current element, or the previous min_product
multiplied by the current element.min_product
to the minimum value among the current element, the previous max_product
multiplied by the current element, or the previous min_product
multiplied by the current element.After updating max_product
and min_product
, update result
to the maximum value among result
and max_product
.
Finally, return result
as the maximum product of any contiguous subarray within nums
.
Here's the implementation of the solution in Python:
from typing import List
def maxProduct(nums: List[int]) -> int:
if not nums:
return 0
max_product = nums[0]
min_product = nums[0]
result = nums[0]
for i in range(1, len(nums)):
# Calculate the product at current index
current_product = nums[i]
# Update max_product using current element
temp_max = max(current_product, max_product * current_product, min_product * current_product)
max_product = max(temp_max, current_product)
# Update min_product using current element
temp_min = min(current_product, max_product * current_product, min_product * current_product)
min_product = min(temp_min, current_product)
# Update result to maximum value so far
result = max(result, max_product)
return result
The time complexity of this solution is O(n), where n is the length of the input array nums
, as we iterate over the array once.