leetcode--python --628

628. Maximum product of three numbers

Given an integer array, find the largest product of three numbers in the array, and output this product

The first method is very simple, directly use the python built-in functions to sort, but I feel that if you write like this during the interview, the interviewer will not give you the next round of interview opportunities.

class Solution:
    def maximumProduct(self, nums: List[int]) -> int:
         tem = sorted(nums)
         max_1 = tem[0] * tem[1] * tem[-1]
         max_2 = tem[-3] * tem[-2] * tem[-1]
         return(max(max_1, max_2))

The second method does not use built-in functions. This question can be understood like this: Regardless of whether the array is all positive or all negative, or has positive or negative, we only need to find the first three numbers and the last two small numbers in the array. The maximum product must be the first three positive multiplication and the last two. The small and the first positive are multiplying.

class Solution:
    def maximumProduct(self, nums: List[int]) -> int:
        
        #不用库
        max_1 = -float('inf')
        max_2 = -float('inf')
        max_3 = -float('inf')
        min_1 = float('inf')
        min_2 = float('inf')

        for i in nums:
            if i > max_1:
                max_3 = max_2
                max_2 = max_1
                max_1 = i
            elif i > max_2:
                max_3 = max_2
                max_2 = i
            elif i > max_3:
                max_3 = i

            if i < min_1:
                min_2 = min_1
                min_1 = i
            elif i < min_2:
                min_2 = i 
        return(max(max_1*max_2*max_3, min_1*min_2*max_1))

Guess you like

Origin blog.csdn.net/AWhiteDongDong/article/details/110857738