August 2020
Intermediate to advanced
508 pages
11h 53m
English
These are the solutions to the exercises found in the section, Exercises. The solutions provided here are in JavaScript, but you can find the solutions in Ruby and Python in the code download.[13]
If we sort the numbers, we know that the three greatest numbers will be at the end of the array, and we can just multiply them together. The sorting will take O(N log N):
| | function greatestProductOf3(array) { |
| | array.sort((a, b) => (a < b) ? -1 : 1); |
| | |
| | return array[array.length - 1] * array[array.length - 2] * |
| | array[array.length - 3]; |
| | } |
(This code takes for granted that there are at least three values in the array. You can add code to handle arrays where this is not the case.)
If we presort the array, we can then expect each ...
Read now
Unlock full access