Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 844
Maverick Avatar asked Sep 05 '16 11:09

Maverick


People also ask

How do you find the maximum product of an array?

The only thing to note here is, maximum product can also be obtained by minimum (negative) product ending with the previous element multiplied by this element. For example, in array {12, 2, -3, -5, -6, -2}, when we are at element -2, the maximum product is multiplication of, minimum product ending with -6 and -2.

How do you find the top 2 maximum number of an array?

Take two variables and initiliaze them with zero. Iterate through each element of the array and compare each number against these two number. If current number is greater than maxOne then maxOne = number and maxTwo = maxOne. Otherwise if it only greater than maxTwo then we only update maxTwo with current number.


1 Answers

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

like image 162
User_Targaryen Avatar answered Sep 23 '22 16:09

User_Targaryen