Last active
January 11, 2019 17:17
-
-
Save fhinkel/690f18c8dfcafd2fc51576e4af97e55e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const maxGap = (arr) => { | |
const n = arr.length; | |
let min = Number.POSITIVE_INFINITY; | |
let max = Number.NEGATIVE_INFINITY; | |
for (let i = 0; i < n; i++) { | |
min = Math.min(arr[i], min); | |
max = Math.max(arr[i], max); | |
} | |
let range = max - min; | |
let lowerBound = range / (n - 1); | |
let buckets = []; // n-1 buckets, 2 elements each => linear space complexity | |
for (let i = 0; i < n; i++) { | |
let index = Math.floor((arr[i] - min) / lowerBound); | |
if (!buckets[index]) { | |
buckets[index] = {}; | |
buckets[index].left = arr[i]; | |
buckets[index].right = arr[i]; | |
} else { | |
if (buckets[index].left > arr[i]) { | |
buckets[index].left = arr[i] | |
} | |
if (buckets[index].right < arr[i]) { | |
buckets[index].right = arr[i] | |
} | |
} | |
} | |
let maxDiff = 0; | |
let prev = min; | |
for (let i = 0; i < buckets.length; i++) { | |
if (!buckets[i]) { | |
continue; | |
} | |
if (buckets[i].left - prev > maxDiff) { | |
maxDiff = buckets[i].left - prev; | |
} | |
prev = buckets[i].right; | |
} | |
return maxDiff; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment