原题
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
解法
动态规划.
参考: [Leetcode 152] Maximum Product Subarray
代码
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_to_cur = min_to_cur = product = nums[0]
for n in nums[1:]:
max_to_cur, min_to_cur = max(max_to_cur*n, min_to_cur*n, n), min(max_to_cur*n, min_to_cur*n, n)
product = max(product, max_to_cur)
return product