Maximum Product of Three Numbers — LeetCode

Soren Rood
2 min readJan 28, 2021

Question:

LeetCode #628

Asked at the following companies:

My solution:

4 lines of python

This solution is very simple. All we have to do is sort the list. The front of the list has the largest numbers, while the back of the list will have the smallest numbers (but the largest negative numbers).

For the front of the list, we grab the first 3 elements and multiply then.

For the back of the list, we grab the 0th element, as well as the 2 smallest numbers. We do this because if the 2 largest numbers are both negative, we can multiply them together and get a potentially very large number.

For example, assume the list [1, 2, 3, -100, -200]

If we sort it in reversed order, it would look like this:

[3, 2, 1, -100, -200]

front would be set to 3 * 2 * 1 == 6

back would be set to 3 * -200 * -100 == 60000\

Returning max(front, back) will return the largest number.

Here is the exec report:

Source Code

Social Links

--

--