Given an n-length Array of integers ranging from -1000 to 1000 find the largest product of three numbers in A that you can get.
[-3,2,6,4,8] => 192
There are three basic scenarios that can produce the largest product:
The first task is to sort the array, that means that the largest numbers are at the right and the smallest area on the left.
a | b | c | … | … | … | x | y | z |
Something like this, with a, b and c being the smallest values and x, y, and z being the largest values.
The first scenario happens when x*y
is greater than a*b
. Consequently, the second scenario only occurs when a*b
is greater than x*y
. We will always use z in these two scenarios because it is the largest positive number and two negatives will always give a positive.
The third scenario only occurs when z is less than 0. In this case, we now want the smallest absolute value which happens to be the largest number.
[-4, -5, 1, 2, 7, 9, 10]x * y = 7 * 9 = 63
which is greater thana * b = -5 * -4 = 20
[-9, -8, -7, 1, 2, 3]x * y = 2
which is less thana * b = 72
[-5, -4, -3, -2, -1] z is negative,
This leads to the following code
function solution(A) {
A.sort((a,b) => a-b)
const n = A.length
const positiveProduct = A[n-2] * A[n-3]
const negativeProduct = A[0] * A[1]
if (positiveProduct > negativeProduct || A[n -1] < 0){
return A[n-1] * positiveProduct
}
return A[n-1] * negativeProduct
}
Code language: JavaScript (javascript)
Notes:
const aCopy = [...A];
positiveProduct
and negativeProduct
could be named better.And that’s that.
Today I am working on a summation problem made to look like building a tower out of cubic bricks. It’s fun to brute force sometimes.
Coming back to Rust code after a bit of a hiatus with a simple problem… The Two-sum problem. Finding numbers in an array. Yay, fun.
King Pinn: I Salute You. I’m driving halfway across the country and this song is on repeat. Rest in Peace Tonderai Makoni. You were awesome.
After a few weeks off I’m back to business. This is just an update post detailing plans for the rest of the year.
At last we finally have the great reveal, our mystery project was implementing RSA encryption in rust.