re: Write better code: Day 1 - Highest Product VIEW POST


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:

  1. Highest number
  2. Lowest number
  3. Highest product of two numbers.
  4. Lowest product of two numbers.
  5. Max product of previous 3 numbers.

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.

code of conduct - report abuse