![](/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.