边工作边刷题:70天一遍leetcode: day 7

Maximum Product Subarray

错误点:

  • globalmax应该初始化为-inf,因为可能是negative
  • 因为要分两步更新localmax和localmin,所有要先把旧的localmax存起来以便更新localmin(假设先更新localmax)
class Solution(object):
    def maxProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        localmax = 1
        localmin = 1
        globalmax = -sys.maxint-1
        for i in range(len(nums)):
            oldlocalmax = localmax
            localmax = max(nums[i]*localmax, nums[i]*localmin, nums[i])
            localmin = min(nums[i]*oldlocalmax, nums[i]*localmin, nums[i])

            if localmax > globalmax:
                globalmax = localmax
        return globalmax
posted @ 2016-05-18 10:24  absolute100  阅读(96)  评论(0编辑  收藏  举报