码迷,mamicode.com
首页 > 编程语言 > 详细

628. Maximum Product of Three Numbers@python

时间:2018-09-30 14:41:36      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:numbers   lis   a*   复杂   turn   两种   难度   一个   nts   

Given an integer array, find three numbers whose product is maximum and output the maximum product.

Note:

  1. The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
  2. 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

标签:numbers   lis   a*   复杂   turn   两种   难度   一个   nts   

原文地址:https://www.cnblogs.com/chimpan/p/9728933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!