August 2024
Intermediate to advanced
516 pages
11h 47m
English
These are the solutions to the exercises found in the section Exercises.
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); |
| | |
| | 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 number to be at its own index. That is, the 0 should be at index 0, the 1 should be at index 1, and so on. We can then iterate through ...
Read now
Unlock full access