Skip to content

Instantly share code, notes, and snippets.

@gushogg-blake
Last active April 16, 2020 08:59
Show Gist options
  • Save gushogg-blake/4567e61587219ff39d27db04647e754e to your computer and use it in GitHub Desktop.
Save gushogg-blake/4567e61587219ff39d27db04647e754e to your computer and use it in GitHub Desktop.
function nextIncreasingValues(array) {
let nivs = [];
for (let i = array.length - 1; i >= 0; i--) {
let currentNumber = array[i];
let niv;
if (i === array.length - 1) {
// the last element always has a NIV of -1
niv = -1;
} else {
let nextNumber = array[i + 1];
let nextNumbersNiv = nivs[i + 1];
if (nextNumber > currentNumber) {
// the next number is bigger, so that's the niv
niv = nextNumber;
} else if (nextNumbersNiv > currentNumber) {
// the next number is not bigger but has a niv that's bigger, so that's the niv
niv = nextNumbersNiv;
} else {
// the next number is smaller and so is its niv, so there is no niv
niv = -1;
}
}
nivs[i] = niv;
}
return nivs;
}
// test
let numbers = [4, 3, 4, 5];
let expectedNivs = [5, 4, 5, -1];
let nivs = nextIncreasingValues(numbers);
console.log(expectedNivs); // [ 5, 4, 5, -1 ]
console.log(nivs); // [ -1, 4, 5, -1 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment