Skip to content

Instantly share code, notes, and snippets.

@mattrajca
Created March 6, 2015 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattrajca/a67d88933a8cdcd304f8 to your computer and use it in GitHub Desktop.
Save mattrajca/a67d88933a8cdcd304f8 to your computer and use it in GitHub Desktop.
Compute length of longest increasing subsequence in Swift
// Playground - noun: a place where people can play
let array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 8, 4, 6, 2, 7]
// Computes the length of the longest increasing subsequence in the list of integers.
func lis(list: [Int]) -> Int {
return lis(0, list, nil)
}
func lis(index: Int, list: [Int], largestValue: Int?) -> Int {
if index >= list.count {
return 0
}
let currentValue = list[index]
if currentValue <= largestValue {
return lis(index + 1, list, largestValue)
}
return max(lis(index + 1, list, largestValue == nil ? currentValue : largestValue), lis(index + 1, list, currentValue) + 1)
}
lis(array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment