【LeetCode】628. Maximum Product of Three Numbers 解題報告(Python)

做者: 負雪明燭
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:排序

  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.

題目大意

從一個數組中找出三個數字,求這三個數字的乘積是最大的值。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 日 —— 美妙的週末,美麗的天氣