Maximum Prodyct Subarray Leetcode Python

来源:互联网 发布:淘宝上的百度财富 编辑:程序博客网 时间:2024/05/29 11:01
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.



这道题目的解法是分别从左边和右边依次乘,如果得到的值大于maxproduct就将其赋值给maxproduct.

可以证明最大值不可能在中间产生。

we multiply from the left and right maintain the maximum value. We can see that the maximum value will not come from the middle.


the code is as follow

class Solution:    # @param A, a list of integers    # @return an integer    def maxProduct(self, A):        maxp=-100000        val=1        for index in range(len(A)):            if val==0:                val=1            val=val*A[index]            if val>maxp:                maxp=val        val=1        for index in reversed(range(len(A))):            if val==0:                val=1            val=val*A[index]            if val>maxp:                maxp=val        return maxp



0 0
原创粉丝点击