LeetCode/Problems

LeetCode 628. Maximum Product of Three Numbers

벤진[Benzene] 2020. 7. 9. 10:11

Problem:

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.

-Summary-

1. Sort the array.

2. We have two cases possible for the maximum product of three numbers in sorted arrays.

   - Last 3 numbers with positive integers.

   - Two negative numbers and the last positive integer.

  *If all numbers are negative, the last three numbers will always maximum product of the three numbers.

3. Compare then return to the max number.

class Solution:
    def maximumProduct(self, nums: List[int]) -> int:
        nums.sort()
        
        maxNum1 = nums[-1] * nums[-2] * nums[-3]
        maxNum2 = nums[-1] * nums[0] * nums[1]
        
        return max(maxNum1, maxNum2)

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]