628. Maximum Product of Three Numbers@python
阿新 • • 發佈:2018-09-30
output product eas tps com maximum tar blank find
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Note:
- The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
- Multiplication of any three numbers in the input won‘t exceed the range of 32-bit signed integer.
原題地址: Maximum Product of Three Numbers
難度: Easy
題意: 找出相乘最大的三個數
思路:
因為數字有正有負,因此相乘最大的三個數分為兩種情況:
(1)最大的三個正數
(2)最小的兩個負數以及一個最大的正數
代碼:
class Solution(object): def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ a = b = c = None d= e = 0x7FFFFFFF for i in range(len(nums)): if nums[i] >= a: # 找出最大的三個數 a, b, c = nums[i], a, b elif nums[i] >= b: b, c = nums[i], b elif nums[i] >= c: c = nums[i] if nums[i] <= e: # 找出最小的兩個數d, e = e, nums[i] elif nums[i] <= d: d = nums[i] max_val = 0 # if a > 0 and b > 0 and c > 0: # max_val = max(max_val, a * b * c) # if a > 0 and d < 0 and e < 0: # max_val = max(max_val, a * d * e) # if a < 0 and b < 0 and c < 0: # max_val = a * b * c max_val = max(a*b*c, a*d*e) return max_val
時間復雜度: O(n)
空間復雜度: O(1)
628. Maximum Product of Three Numbers@python