kennymkchan / interview-questions-in-javascript

A mostly reasonable collection of technical software development interview questions solved in Javascript
MIT License
3.61k stars 441 forks source link

1.1 - why is greatest product either (min1 * min2 * max1 || max1 * max2 * max3) #21

Closed gotofritz closed 7 years ago

gotofritz commented 7 years ago

Hi. Looking at https://github.com/kennymkchan/interview-questions-in-javascript#array--product, a comemnt says // greatest product is either (min1 * min2 * max1 || max1 * max2 * max3) Surely the greatest product is the one with from max1 max2 max3, where does min1 min2 max1 come from? Or am I missing something?

function computeProduct(raw_data) {
    return raw_data
            .sort((a, b) => Math.abs(a) - Math.abs(b))
            .slice(-3)
            .reduce((accumulator, num) => accumulator * num);
}
kennymkchan commented 7 years ago

If you have negative numbers, your array could be:

[-40, -20, 1, 2, 3]. The greatest product in this case would be (-40)(-20)(3), not (1)(2)(3). Notice that the negatives would cancel out in this case.

@gotofritz

kennymkchan commented 7 years ago

Closing! 😄