pairwise maximum product

So I started doing the Coursera course for Algorithsm, mostly since I was spending a lot of time on SNS and not really learning anything. I thought to might as well start with a lil programming since I have long left it tbh.

For the first week of the course, I had a very simple problem statement

In this problem, we’re given an array, or a sequence of n numbers.¬†And our goal is to find a number which can be obtained¬†by multiplying some two numbers from this sequence.

So there would be two inputs when you run the program like –


1 2 3

The output should be the largest number, which is a multiplication of the pair, in this case it would be 6.

For another sample input


-10000 -20000 10 20

The output would be 20000000 because multiplying two negative numbers gives you a positive number. I was able to solve it however only after doing a stress test with multiple implementations and matching the results of each one. It really did take a lot of time to reach the answer or maybe I wasted a lot of time in not going to the stress test option first.

Below is a working and 100% successfuly solution. Do try it out and let me know if you guys have any problems running it.

require 'bigdecimal'
# Input the number of numbers
n = readline
# Input the list of numbers
array_list = readline.split(' ')
# Initializing the variables
max1 = BigDecimal("0")
max2 = BigDecimal("0")
min1 = BigDecimal("0")
min2 = BigDecimal("0")
min1_index = 0
max1_index = 0
# Finding the Biggest and Smallest Number and storing their index
array_list.each_with_index do |value, index|
if BigDecimal(value) > 0
if max1 < BigDecimal(value)
max1 = BigDecimal(value)
max1_index = index
if BigDecimal(value) < 0
if min1 < BigDecimal(value) * –1
min1 = BigDecimal(value) * –1
min1_index = index
#Finding the second biggest and smallest numbers.
array_list.each_with_index do |value, index|
if BigDecimal(value) > 0
max2 = BigDecimal(value) if BigDecimal(value) <= max1 and BigDecimal(value) > max2 and max1_index != index
if BigDecimal(value) < 0
min2 = BigDecimal(value) * –1 if BigDecimal(value) >= min1 * –1 and BigDecimal(value) < min2 * –1 and min1_index != index
#Checking if any of them is 0, else multiplying them accordingly
if( min1 != 0 or min2!= 0 or max1 != 0 or max2 !=0)
if(max1 * max2 < min1 * min2)
result1 = (min1 * min2)
result1 = (max1 * max2)
result1 = min1 * max1
#outputting to a format to pass the tests in Coursera
puts result1.to_s("F").split(".")[0]