我在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 itertoolsbinations(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更多推荐
如何在列表中找到两个元素的最大乘积?
发布评论