Last active
September 4, 2021 19:33
-
-
Save YonatanKra/84c6236ded2cf8fb384e485aa354d68f 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
function getNestedArraysMaxLength(inputArray) { | |
let maxLength = -Infinity; | |
const memory = []; | |
inputArray.forEach(value => { | |
memory[value] = findSeriesLength(inputArray, value, memory); | |
maxLength = Math.max(maxLength, memory[value]); | |
}); | |
return maxLength; | |
} | |
function findSeriesLength(arr, nextValue, memory) { | |
const series = {[nextValue]: true}; | |
while (true) { | |
nextValue = arr[nextValue]; | |
if (memory[nextValue]) { | |
return memory[nextValue]; | |
} | |
if (series[nextValue]) { | |
return Object.keys(series).length; | |
} | |
series[nextValue] = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment