Created
March 6, 2015 15:58
-
-
Save mattrajca/a67d88933a8cdcd304f8 to your computer and use it in GitHub Desktop.
Compute length of longest increasing subsequence in Swift
This file contains hidden or 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
// 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