美文网首页
152. Maximum Product Subarray

152. Maximum Product Subarray

作者: JERORO_ | 来源:发表于2018-06-27 20:47 被阅读0次

问题描述

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
Example 2:
Input: [-2,0,-1]
Output: 0

思路:

loop一遍,用三个值minimaxi(某一区间),和ans(最终return的值)

  1. 对于每个数字,如果小于0,交换minimaxi的值,因为乘负数大的变小,小的变大
  2. 其次,mini = min(mini*i, i), maxi = max(maxi*i, i), 看这个区间还能不能乘出新的maximini
  3. ans每次确认是否需要更新
    def maxProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return
        mini = maxi = ans = nums[0]

        for i in nums[1:]:
            if i < 0:
                tmp = mini
                mini = maxi
                maxi = tmp
            mini = min(i * mini, i)
            maxi = max(i * maxi, i)
            ans = max(ans, maxi)
        return ans   

相关文章

网友评论

      本文标题:152. Maximum Product Subarray

      本文链接:https://www.haomeiwen.com/subject/daviyftx.html