Maximum Product of Three Numbers

In pseudocode, 0x7FFFFFFF would be rendered as infinity (and None, as minus infinity). The proof of correctness is a lemma to the effect that the three numbers with the greatest product can be found among the greatest three and the least two. Plus/minus infinity serves as a sentinel value for the min/max two/three values, to be replaced shortly by actual values once the first three have been scanned.

1001 would work as well.


In addition to the @David Eisenstat answer, few additional comments:

  • Considering None as minus infinity is something that will work on python2 but it'll raise an exception in python3, for instance:

In early Python, the decision was made that the comparison of any two objects was legal and would return a consistent result. So objects of different types will compare according to an ordering on their types (an implementation dependent, unspecified, but consistent ordering), and objects of the same type will be compared according to rules that make sense for that type.

Other implementations have the right to compare an integer and None differently, but on a specific implementation, the result will not change.

Python 3 will raise an exception on such comparisons.

  • You're correct, 0x7FFFFFFF would be the equivalent to the max signed int, sys.maxsize == 0x7FFFFFFF

  • In python2 you can make the next comparisons, both 0x7FFFFFFF>(1000*1000*1000) and None<-(1000*1000*1000) are True, so using 0x7FFFFFFF as upper bound and None as lower bound is just fine, although other bounds would be correct as well

  • That said, I'd suggest you refactor that code to make it work also in python3 :)


Taking the following example: [-999, -999, 100, 200, 300], the answer is to take -999, -999 and 300 (and not simply the product of the 3 largest numbers).

As a consequence, you need to store:

  • the 3 largest numbers (pa, pb, pc)
  • the 2 smallest numbers (na, nb)

The result is the greatest value between pa * na * nb and pa * pb * pc.

0x7FFFFFFF is just a very big number used to find the smallest values. Since the greatest possible value is 1000, 1000 could have been used instead.

Similarly, the author used None to initialize pa, pb and pc. The author could have used -1000 instead.