Maximum Product Subarray
Examples
Example 1:
Input: nums = [1,2,-3,4]
Output: 4
Example 2:
Input: nums = [-2,-1]
Output: 2
Example 1:
Input: nums = [1,2,-3,4]
Output: 4
Example 2:
Input: nums = [-2,-1]
Output: 2
Given an integer array nums, find a subarray that has the largest product within the array and return it.
A subarray is a contiguous non-empty sequence of elements within an array.
You can assume the output will fit into a 32-bit integer.
1 <= nums.length <= 1000-10 <= nums[i] <= 10Track both the maximum and minimum product ending at each position, because multiplying by a negative number swaps them. Update these values as you scan the array and keep the global maximum.
The maximum product subarray ending at index i is either the current number alone or the current number times the previous max/min (depending on sign). Tracking both extremes captures all possibilities, and the global maximum over all endings is the answer.
O(n)O(1)class Solution:
def maxProduct(self, nums: List[int]) -> int:
max_prod = min_prod = ans = nums[0]
for num in nums[1:]:
if num < 0:
max_prod, min_prod = min_prod, max_prod
max_prod = max(num, max_prod * num)
min_prod = min(num, min_prod * num)
ans = max(ans, max_prod)
return ans