【LeetCode每天一题】Maximum Product Subarray(子数组的最大积)

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.


思路

  这道题给我们一个数组,需要求出连续子数组最大积。一开始看到这道题的时候我想到了暴力破解法,对每一种组合进行计算,计算得出最大的积。这种解法的时间复杂度为O(n2), 空间复杂度为O(1)。
  上面的思路可以破解数量不是很大的情况,当数据量很大时,会存在超时问题。因此还有更好的解决办法。自己没能想出来,看了别人的解决办法,利用两个变量记录到当前下标时最大的积和最小的积。另外一个变量记录结果。数组的第二个元素开始遍历,一直遍历到数组尾部。时间复杂度为O(n),空间复杂度为O(1)。
解决代码

第一种思路解决代码
 1 class Solution(object):
 2     def maxProduct(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         if not nums:
 8             return 
 9         max_res = nums[0]
10         for i in range(len(nums)):    # 从数组头开始遍历
11             tem = nums[i]            # tem记录中间乘积结果
12             if tem > max_res:         # 反之最后一个元素是最大的结果
13                 max_res = tem
14             for j in range(i+1, len(nums)):  # 从i的下一个元素开始遍历
15                 tem = tem * nums[j]      
16                 if tem > max_res:    # 比较
17                     max_res = tem
19         return max_res

第二种思路

 1 class Solution(object):
 2     def maxProduct(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         small= big = res = nums[0]      # small表示最小的乘积(为了防止两个负数相乘大于结果集), big表示最大的乘积, res表示结果
 8         for i in nums[1:]:              # 从第二个元素开始遍历
 9             big, small = max(i*big, i*small, i), min(i*big, i*small, i)    # 分别取最大的乘积, 最小的乘积
10             res= max(big, res)          # 更新结果
11         return res
原文地址:https://www.cnblogs.com/GoodRnne/p/10980112.html