Created
November 30, 2016 02:47
-
-
Save subdigital/8e7761b915cd7d0ce2fba65aa54737cc to your computer and use it in GitHub Desktop.
Given a sorted array of ints, returns the largest consecutive streak contained.
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
func largestSeq(values: [Int]) -> Int { | |
let initial: (current: Int, max: Int, prev: Int?) = (0, 0, nil) | |
let result = values.reduce(initial) { acc, el in | |
if acc.prev == nil { | |
return (1, 1, el) | |
} | |
let current = el - acc.prev! == 1 ? acc.current + 1 : 1 | |
let newMax = max(current, acc.max) | |
return (current, newMax, el) | |
} | |
return result.max | |
} | |
largestSeq(values: []) // 0 | |
largestSeq(values: [0]) // 1 | |
largestSeq(values: [1, 2, 3, 4, 5]) // 5 | |
largestSeq(values: [1, 2, 3, 8, 9, 10, 11]) // 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment