【python3】leetcode 628. Maximum Product of Three Numbers(easy)

120 篇文章 0 订阅

628. Maximum Product of Three Numbers(easy)

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

注意是会有负数

1 暴力破解

考虑4种情况:

nums里只有三个数时:直接返回这三个数的乘积,啥都不用考虑

nums里有》4个数时考虑:

    只有一个正数,》3个负数时:返回 最小的两个负数和正数的乘积保证乘积为最大正数

    有两个正数时:说明必须乘一个负数,那就只能乘最大负数保证乘积为最大负数

    在有三个以上正数时:考虑2负1正,3正哪个比较大

class Solution:
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        sortnum = sorted(nums)
        if length == 3:return nums[0]*nums[1]*nums[2]
        neg = [i for i in sortnum if i < 0]
        pos = [i for i in sortnum if i >=0]
        if len(neg) == 1 or len(neg) == 0:return  sortnum[-1]*sortnum[-2]*sortnum[-3]
        elif len(pos) == 1: return neg[0] * neg[1] * pos[-1]
        elif len(neg) >= 2:
            negpro = neg[0] * neg[1] * pos[-1]
            pospro = pos[-1] * pos[-2] * pos[-3]
            if(negpro > pospro):return negpro
            else:return pospro

Runtime: 124 ms, faster than 27.38% of Python3 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值