[LeetCode]Maximum Product of Three Numbers

题目描述:

LeetCode  628. Maximum Product of Three Numbers

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

Example 1:

Input: [1,2,3]
Output: 6

Example 2:

Input: [1,2,3,4]
Output: 24

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.

题目大意:

给定整数数组,计算其中三个数字相乘的最大值。

解题思路:

线性遍历 时间复杂度O(n)

变量na, nb存储最小元素,变量pa, pb, pc存储最大元素

取pa * na * nb, pa * pb * pc的最大值

Python代码:

class Solution(object):
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans = pa = pb = pc = None
        na = nb = 0x7FFFFFFF
        for n in nums:
            if n > pa: pa, pb, pc = n, pa, pb
            elif n > pb: pb, pc = n, pb
            elif n > pc: pc = n
            if n < na: na, nb = n, na
            elif n < nb: nb = n
        return max(ans, pa * na * nb, pa * pb * pc)

 

本文链接:http://bookshadow.com/weblog/2017/06/25/leetcode-maximum-product-of-three-numbers/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

评论
  1. 书影网友 书影网友 发布于 2017年7月1日 03:40 #

    why do u need to check na*nb*nc? it should be either negative or zero.

  2. 书影网友 书影网友 发布于 2017年7月1日 19:04 #

    感谢提醒!之前的代码有Bug,已经更正 :)

张贴您的评论