This task is taken from www.interviewbit.com
Given an array of integers, return the highest product possible by multiplying 3 numbers from the array
Input:
array of integers e.g {1, 2, 3}
Example:
[0, -1, 3, 100, 70, 50] => 70*50*100 = 350000
NOTE: Solution will fit in a 32-bit signed integer
My approach: First sort the array, then return the maximum the following numbers: The product of the first two smallest numbers (because they could be negative) and the last number (largest) or the product of the three largest numbers.
My solution has a runtime of \$O(n \log n)\$ due to the sort and a space complexity of \$O(1)\$. I wonder whether there is a faster solution than \$O(n\log n)\$.
function highesProd(a) {
a.sort((a,b) => a - b);
return Math.max(a[0] * a[1] * a[a.length - 1], a[a.length - 3] * a[a.length - 2] * a[a.length - 1]);
}
I wonder whether there is a faster solution than O(nlogn).
Use an O(n) algorithm for k largest (smallest). As a matter of say what you mean (and don't repeat yourself), put* a[a.length - 1]
outside themax()
. \$\endgroup\$