如何在列表中找到两个元素的最大乘积? [英] How to find the maximum product of two elements in a list?

查看:57
本文介绍了如何在列表中找到两个元素的最大乘积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在hackerrank竞赛中尝试了一个有趣的问题,然后出现了这个问题. 我为此使用了itertools,这是代码:

I was trying out a problem on hackerrank contest for fun, and there came this question. I used itertools for this, here is the code:

import itertools

l = []

for _ in range(int(input())):
    l.append(int(input()))


max = l[0] * l[len(l)-1]

for a,b in itertools.combinations(l,2):
    if max < (a*b):
        max = (a*b)
print(max)

他们还有其他有效的方法吗?当我在某些无法访问的测试用例上遇到超时错误时(这是一次小竞赛).

Is their any other efficient way than this? As I am getting time out error on some test cases which I cant access (as its a small contest).

推荐答案

这里是遵循@User_Targaryen逻辑的实现. heapq 返回列表中的2个最大和2个最小的数字, mul operator 返回这两个数字对的乘积,而max返回这两个产品中最大的一个.

Here is an implementation following @User_Targaryen's logic. heapq returns the 2 largest and 2 smallest numbers in the list, mul operator returns the products of these 2 pairs of numbers, and max returns the largest of these 2 products.

>>> import heapq
>>> from operator import mul
>>> l = [2,40,600,3,-89,-899]
>>> max(mul(*heapq.nsmallest(2,l)),mul(*heapq.nlargest(2,l)))
80011
# -899*-89 = 80011

这篇关于如何在列表中找到两个元素的最大乘积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆