Description
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.
Code(mzchen )
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
imax = imin = res = nums[0]
for i in nums[1:]:
if i < 0:
imax, imin = imin, imax
imax = max(i, i * imax)
imin = min(i, i * imin)
res = max(res, imax)
return res
算法真的屌,光是看我都没看懂。手动跑了一遍,感觉好像理解了。这个算法屌在同时记录了max和min,当遇到负数时可以将二者swap一下(这里学习了python中swap的方法: a, b = b, a),就简单快捷的应对了负数的情况。
Conclusion
自己刚看到这个题目的时候直接就懵逼了,一直在想数列中负数为奇怎样怎样,为偶怎样怎样,直接方向就偏了,陷入细节中去了。学习了大神的算法后,回头想想,假如这是一道数学题,让我人来做,我的做法其实就是大神的这个算法,而不是我之前瞎想的标记负数的位置,统计负数的奇偶,啥啥的。
以后遇到类似的题,还是先想想人来做是怎么做的,然后写代码去实现。