Created
June 16, 2022 16:00
-
-
Save vasigorc/b373741946feba87f886c6fee24d5354 to your computer and use it in GitHub Desktop.
Interview exercise. Find the longest subsequence in an array
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
object FindLIS { | |
def findLIS(initialArray: Array[Int]): Int = { | |
if (initialArray.length < 2) return initialArray.length | |
val allSubSequences = initialArray.zipWithIndex.foldLeft(List.empty[Array[Int]]) { | |
case (currentSubSequences, (nextValue, index)) => | |
currentSubSequences ::: getSubsequenceFromArray(Array(nextValue), initialArray.drop(index)) | |
} | |
allSubSequences.maxBy(_.length).length | |
} | |
private def getSubsequenceFromArray(accumulator: Array[Int], remainder: Array[Int]): List[Array[Int]] = { | |
if (remainder.isEmpty) return List(accumulator) | |
val nextElement = remainder.head | |
if (nextElement > accumulator.last) | |
getSubsequenceFromArray(accumulator :+ nextElement, remainder.tail) ::: getSubsequenceFromArray( | |
accumulator, | |
remainder.tail | |
) | |
else | |
getSubsequenceFromArray(accumulator, remainder.tail) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment