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>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:</p>

<pre><code>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:]))
</code></pre>

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

python python-2.7 python-3.x itertools