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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With