Here is the interview question prompt, presented for reference.
Given an unsorted array of integers, can you write a method maxProductOfThree(unsorted: array)
to find the largest product from three of the numbers? For example, given the following array:
[-1, 9, 22, 3, -15, -7]
The largest product of three numbers is 2310
. This results from -15 * -7 * 22
.
100000
-1000
and 1000
O(n * log n)
O(1)
You can see the full challenge with visuals at this link.
Challenges • Asked over 5 years ago by Anonymous
This is the main discussion thread generated for Max Product Of Three Numbers.
Since you sort the algorithm you provided in O(nlogn) but if you just iterated once to find the first max product, then iterated again to find the second product, it would by O(n).
This question and its solution are a bit misleading. In the question one of the constraints is an O(n) time complexity, but as pointed out by another comment, because you sort the best you can do is O(nlogn). The solution provided as an example does not meet the constraint laid out in the question.