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:
- The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
- 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]
'LeetCode > Problems' 카테고리의 다른 글
LeetCode 819. Most Common Word (0) | 2020.08.18 |
---|---|
LeetCode 937. Reorder Data in Log Files (0) | 2020.08.17 |
LeetCode 91. Decode Ways (0) | 2020.06.21 |
LeetCode 226. Invert Binary Tree (0) | 2020.06.20 |
Daily Coding Problem #5 (0) | 2020.06.19 |
댓글