天天看点

50 leetcode - Maximum Product Subarray

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Maximum Product Subarray.最大乘积的连续子数组
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
'''
class Solution(object):
    def maxProduct(self, nums):
        """
        这种方法超过时间限制
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        if length == :
            return 

        max = nums[]
        for index,val in enumerate(nums):
            sum = 
            for val2 in nums[index:]:
                sum = sum * val2
                if sum > max:
                    max = sum

        return max
    '''其实子数组乘积最大值的可能性为:累乘的最大值碰到了一个正数;或者,累乘的最小值(负数),碰到了一个负数。所以每次要保存累乘的最大(正数)和最小值(负数)。
       同时还有一个选择起点的逻辑,如果之前的最大和最小值同当前元素相乘之后,没有当前元素大(或小)那么当前元素就可作为新的起点。
       例如,前一个元素为0的情况,{1,0,9,2},到9的时候9应该作为一个最大值,也就是新的起点,{1,0,-9,-2}也是同样道理,-9比当前最小值还小,所以更新为当前最小值。'''
    def maxProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        if length == :
            return 

        max_tmp = min_tmp = ret = nums[]
        for val in nums[:]:
            #print max_tmp,min_tmp
            a = max_tmp * val
            b = min_tmp * val
            max_tmp = max(a,b,val)
            min_tmp = min(a,b,val)
            ret = max(ret,max_tmp)
        return ret

if __name__ == "__main__":
    s = Solution()
    print s.maxProduct([,,-,])
    print s.maxProduct([,,-,-])
    print s.maxProduct([,,,])
    print s.maxProduct([,,,])
    print s.maxProduct([,-,-,-,])
           

参考链接:http://blog.csdn.net/worldwindjp/article/details/39826823