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
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
相关文章推荐
- leetcode:Maximum Subarray---python
- Maximum Subarray Leetcode Python
- [leetcode]Maximum Subarray @ Python
- [leetcode]Maximum Product Subarray @ Python
- [LeetCode]Maximum Subarray@python
- [LeetCode]题解(python):152-Maximum Product Subarray
- 【LeetCode with Python】 Maximum Subarray
- LeetCode: Maximum Subarray [052]
- LeetCode :: Maximum Subarray 详细分析
- Leetcode: Maximum Subarray
- Maximum Subarray 最大子数组和(连续)@LeetCode
- [leetcode]Binary Tree Maximum Path Sum @ Python
- Maximum Subarray -- LeetCode
- Leetcode Maximum SubArray & Binary Tree Maximum Path Sum
- 【LeetCode with Python】 Maximum Depth of Binary Tree
- LeetCode刷题笔录Maximum Subarray
- Leetcode Maximum Subarray
- Maximum Subarray [LEETCODE]
- LeetCode: Maximum Subarray
- Leetcode: Maximum Subarray