![](/img/trans.png)
[英]How to find N maximum product subarrays of M elements of a Numpy array?
[英]How to find the maximum product of two elements in a list?
我正试图在hackerrank比赛中找到一个有趣的问题,并且出现了这个问题。 我使用itertools,这是代码:
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)
他们还有其他任何有效的方法吗? 因为我在一些我无法访问的测试用例中得到时间错误(因为它是一个小小的竞赛)。
迭代列表并找到以下内容:
最大正数(a)
第二大正数(b)
最大负数(c)
第二大负数(d)
现在,您将能够计算乘法时的最大值, a*b
或c*d
只需对列表进行排序,然后选择列表中最后2项的最大产品和列表中的前2项:
from operator import mul
numbers = [10, 20, 1, -11, 100, -12]
l = sorted(numbers) # or sort in place with numbers.sort() if you don't mind mutating the list
max_product = max(mul(*l[:2]), mul(*l[-2:]))
由于排序,这是一个O(n log n)解决方案。 其他人提出了一个heapq
解决方案,我发现对于长度超过几千个随机整数的列表来说更快。
这是@ User_Targaryen逻辑之后的实现。 heapq
返回列表中最大的2个和2个最小的数字, mul operator
返回这两对数字的乘积,而max
返回这两个乘积中最大的一个。
>>> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.