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
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
问题本质:
本质:动态规划问题。 局部最优,全局最优。
product-乘法问题,存在的情况是 负数或者正数,或者从当前数开始新的连续元素相乘
可能发生的情况: 在某个节点,继续之前的增大/减小,从此节点转折。
所以只要在局部动态中,保持最大/最小/当前,进行判断保留即可。
应用:挖掘问题的本质,将问题抽象化, 局部:之前的值和当前值是同乡还是异向的问题,同向则被覆盖,异向则被保留。如此迭代。
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
final_max=max_num=min_num=nums[0]
for num_cur in nums[1:]:
# min_num=min(num_cur*min_num,num_cur)
max_num_tmp=max(num_cur*min_num,num_cur*max_num)
min_num=min(num_cur*min_num,num_cur*max_num,num_cur)
max_num=max(max_num_tmp,num_cur)
final_max=max(max_num,final_max)
return final_max
if __name__=='__main__':
st=Solution()
num=[2,3,-2,-5,4,-5,8]
# num=[-2,0,-1]
# num=[2,3,-2,4]
num=[-1,-2,-9,-6]
out=st.maxProduct(num)
print(out)