您的位置:首页 > 编程语言 > Python开发

Maximum Prodyct Subarray Leetcode Python

2015-01-22 01:35 393 查看
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 followclass 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python Array leetcode