Node.js/JavaScript interview training - Sorting

preview_player
Показать описание
We're solving the "Max Gap" problem: Given an unsorted array of numbers, find the maximum difference between the successive elements in its sorted form. Linear time (and linear space)!

Рекомендации по теме
Комментарии
Автор

Incredible problem from a simple prompt

Mrstealurgrill
Автор

/**
* Max difference solution
*/
let myArray = [1, 4, 6, 3, 5, 16]
let sortedArray = myArray.sort((a, b) => a - b)

let prevDiff = 0
let maxDiff = 0
for (let i = 0; i < sortedArray.length; i++) {
let prev = sortedArray[i];
diff = sortedArray[i + 1] - prev;
if (diff > prevDiff) {
maxDiff = diff
}
prevDiff = diff
}
console.log(maxDiff)

samsonanami