DEV Community

Discussion on: Write better code: Day 1 - Highest Product

Collapse
 
arjunrajkumar profile image
Arjun Rajkumar

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.

Code

This is O[n] which is still better than sort which is O[nlogn]

Thread Thread
 
qm3ster profile image
Mihail Malo

Will you believe me if I tell you that I didn't see this comment thread until now (well after posting my fixed solution)?

Thread Thread
 
arjunrajkumar profile image
Arjun Rajkumar

Ofcourse :) Only then would you have tried solving it twice and with a different logic.