Skip to content

Instantly share code, notes, and snippets.

@subdigital
Created November 30, 2016 02:47
Show Gist options
  • Select an option

  • Save subdigital/8e7761b915cd7d0ce2fba65aa54737cc to your computer and use it in GitHub Desktop.

Select an option

Save subdigital/8e7761b915cd7d0ce2fba65aa54737cc to your computer and use it in GitHub Desktop.

Revisions

  1. subdigital created this gist Nov 30, 2016.
    19 changes: 19 additions & 0 deletions largest_sequence.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    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