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 –
3
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
4
-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_indexdo |value,index|
ifBigDecimal(value) > 0
ifmax1 < BigDecimal(value)
max1=BigDecimal(value)
max1_index=index
end
end
ifBigDecimal(value) < 0
ifmin1 < BigDecimal(value) * –1
min1=BigDecimal(value) * –1
min1_index=index
end
end
end
#Finding the second biggest and smallest numbers.
array_list.each_with_indexdo |value,index|
ifBigDecimal(value) > 0
max2=BigDecimal(value)ifBigDecimal(value) <= max1andBigDecimal(value) > max2andmax1_index != index