Skip to content

Instantly share code, notes, and snippets.

@vasigorc
Created June 16, 2022 16:00
Show Gist options
  • Save vasigorc/b373741946feba87f886c6fee24d5354 to your computer and use it in GitHub Desktop.
Save vasigorc/b373741946feba87f886c6fee24d5354 to your computer and use it in GitHub Desktop.
Interview exercise. Find the longest subsequence in an array
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