Just realised that my original attempt was wrong !
For two negative integers e.g [-5, -4, 1, 3, 2] the correct answer is 60.
But the code above gives 6.
So.. need to change.
Ended up doing this by checking if the product of current number with the previous stored two numbers is greater than the the current max.
Had to store 5 variables:
Then with each new number I check if the max product is greater than previous, and also update each. As there are negative numbers, the lowest product of two numbers can suddenly give the max product when multiplied with the current.
This is O[n] which is still better than sort which is O[nlogn]
Will you believe me if I tell you that I didn't see this comment thread until now (well after posting my fixed solution)?
Ofcourse :) Only then would you have tried solving it twice and with a different logic.
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.