Skip to content

Instantly share code, notes, and snippets.

@lndgalante
Last active March 12, 2024 01:21
Show Gist options
  • Select an option

  • Save lndgalante/eb6b711f3d18d261ebafcc719d214d99 to your computer and use it in GitHub Desktop.

Select an option

Save lndgalante/eb6b711f3d18d261ebafcc719d214d99 to your computer and use it in GitHub Desktop.
max gap challenge
/*
Given an integer array arr, return the maximum difference between two successive elements in arr's sorted form. Return 0 if there's 0 or 1 elements.
*/
function maxGap(numbers: number[]): number {
if ([0, 1].includes(numbers.length)) {
return 0;
}
const differences = numbers
.toSorted((a, b) => a - b)
.map((number, index, array) => array[index + 1] - number)
.filter(Boolean);
const maximumDifference = Math.max(...differences);
return maximumDifference;
}
console.log("maxGap", maxGap([3, 6, 9, 1, 2]));
//3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment