1. 程式人生 > >【python3】leetcode 628. Maximum Product of Three Numbers(easy)

【python3】leetcode 628. Maximum Product of Three Numbers(easy)

628. Maximum Product of Three Numbers(easy)

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

注意是會有負數

1 暴力破解

考慮4種情況:

nums裡只有三個數時:直接返回這三個數的乘積,啥都不用考慮

nums裡有》4個數時考慮:

    只有一個正數,》3個負數時:返回 最小的兩個負數和正數的乘積保證乘積為最大正數

    有兩個正數時:說明必須乘一個負數,那就只能乘最大負數保證乘積為最大負數

    在有三個以上正數時:考慮2負1正,3正哪個比較大

class Solution:
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        sortnum = sorted(nums)
        if length == 3:return nums[0]*nums[1]*nums[2]
        neg = [i for i in sortnum if i < 0]
        pos = [i for i in sortnum if i >=0]
        if len(neg) == 1 or len(neg) == 0:return  sortnum[-1]*sortnum[-2]*sortnum[-3]
        elif len(pos) == 1: return neg[0] * neg[1] * pos[-1]
        elif len(neg) >= 2:
            negpro = neg[0] * neg[1] * pos[-1]
            pospro = pos[-1] * pos[-2] * pos[-3]
            if(negpro > pospro):return negpro
            else:return pospro

Runtime: 124 ms, faster than 27.38% of Python3