Skip to content

Instantly share code, notes, and snippets.

@subdigital
Created November 30, 2016 02:47
Show Gist options
  • Save subdigital/8e7761b915cd7d0ce2fba65aa54737cc to your computer and use it in GitHub Desktop.
Save subdigital/8e7761b915cd7d0ce2fba65aa54737cc to your computer and use it in GitHub Desktop.
Given a sorted array of ints, returns the largest consecutive streak contained.
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