How to find the maximum product of two elements in a list?

梦想与她 提交于 2019-12-06 03:57:24

问题


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).


回答1:


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



回答2:


Iterate over the list and find the following:

Largest Positive number(a)

Second Largest Positive number(b)

Largest Negative number(c)

Second Largest Negative number(d)

Now, you will be able to figure out the maximum value upon multiplication, either a*b or c*d




回答3:


Just sort the list and select the largest of the products of the last 2 items in the list and the first 2 items in the list:

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:]))

This is a O(n log n) solution due to the sort. Someone else suggested a heapq solution which I found to be faster for lists longer than a few thousand random integers.



来源:https://stackoverflow.com/questions/39329829/how-to-find-the-maximum-product-of-two-elements-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!