做者: 负雪明烛
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.cn/python
题目地址:https://leetcode.com/problems/maximum-product-of-three-numbers/description/数组
Given an integer array, find three numbers whose product is maximum and output the maximum product.ide
Example 1:spa
Input: [1,2,3] Output: 6
Example 2:code
Input: [1,2,3,4] Output: 24
Note:排序
从一个数组中找出三个数字,求这三个数字的乘积是最大的值。three
这个题要求数组中三个数乘积最大的值。我以为能够从为何问3个数字而不是其余数字去考虑。ip
输入有可能存在负值,因此3个数字的乘积时会考虑到负负得正的状况。只有三个数都是正数或者有只有两个负数时获得的结果是正的。这样,首先经过排序,获得最右边三个数的乘积,和最小的两个负数(若是存在负数)和最大数字的乘积,比较两个乘积的大小就好了。element
若是排序后取到的三个数存在奇数个负数也不要紧,咱们取最大值的时候会保证取到最大的。leetcode
class Solution(object): def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() right = nums[-3] * nums[-2] * nums[-1] left = nums[0] * nums[1] * nums[-1] return max(left, right)
2018 年 1 月 26 日 2018 年 11 月 17 日 —— 美妙的周末,美丽的天气