How does leetcode calculate the maximum product of three numbers
This article mainly introduces "how leetcode calculates the maximum product of three numbers". In daily operation, I believe that many people have doubts about how leetcode calculates the maximum product of three numbers. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "how leetcode calculates the maximum product of three numbers". Next, please follow the editor to study!
I. the content of the topic
Given an integer array, find the maximum product of three numbers in the array and output the product.
Example 1:
Input: [1Jing 2Jue 3]
Output: 6
Example 2:
Input: [1, 2, 3, 4]
Output: 24
Note:
The given integer array length range is [3104], and all elements in the array range is [- 1000, 1000].
The product of any three numbers in the input array does not exceed the range of 32-bit signed integers.
Second, the way to solve the problem
There is nothing to say, the maximum product after sorting is either the product of the last three numbers, or the product of the first two numbers and then the product of the last number (negative is positive).
Code class Solution: def maximumProduct (self, nums: list)-> int: nums.sort () return max (nums [- 1] * nums [- 2] * nums [- 3], nums [0] * nums [1] * nums [- 1]) if _ name__ = ='_ main__': nums = [1, 2, 3, 4] s = Solution () ans = s.maximumProduct (nums) print (ans) The study on "how leetcode calculates the maximum product of three numbers" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!