[leetcode] 152. Maximum Product Subarray @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/87928750

原题

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

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/87928750