Leetcode_ dynamic programming _152. Product of the maximum subsequence

152. The product of the maximum sequence

Here Insert Picture Description
Idea:
to sum up, that is, the product of the maximum subsequence top n divided into the following three cases:

  1. Before n - a product of the product of a minimal sequence * A [n] Maximum

  2. Before n - a product of the maximum subsequence product * A [n] Maximum

  3. Before n - product * A [n] 1-bit sequence and the product of the maximum product of the smallest sub-sequence is not the maximum, and A [n] itself is the largest.
    Answers 1
    Answers 2

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        length = len(nums)
        if length == 0:
            return 0
        if length == 1:
            return nums[0]
        productmax = [0 for i in range(length)]
        productmin = [0 for i in range(length)]
        productmax[0] = nums[0]
        productmin[0] = nums[0]

        for i in range(length):
            productmax[i] = max(nums[i], nums[i]*productmax[i-1], nums[i]*productmin[i-1])
            productmin[i] = min(nums[i], nums[i]*productmax[i-1], nums[i]*productmin[i-1])

        return max(productmax)
Published 31 original articles · won praise 0 · Views 729

Guess you like

Origin blog.csdn.net/freedomUSTB/article/details/105031892