How to find the maximum product of two elements in a list?
<p>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:</p>

<pre><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 &lt; (a*b):
        max = (a*b)
print(max)
</code></pre>

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

<p>Here is an implementation following @User_Targaryen's logic. <a href="https://docs.python.org/3.0/library/heapq.html" rel="nofollow"><code>heapq</code></a> returns the 2 largest and 2 smallest numbers in the list, <a href="https://docs.python.org/3/library/operator.html" rel="nofollow"><code>mul operator</code></a> returns the products of these 2 pairs of numbers, and <code>max</code> returns the largest of these 2 products.</p>

<pre><code>&gt;&gt;&gt; import heapq
&gt;&gt;&gt; from operator import mul
&gt;&gt;&gt; l = [2,40,600,3,-89,-899]
&gt;&gt;&gt; max(mul(*heapq.nsmallest(2,l)),mul(*heapq.nlargest(2,l)))
80011
# -899*-89 = 80011
</code></pre>

python python-2.7 python-3.x itertools