Swift: Given a list of integers and a number K, return which contiguous elements of the list sum to K - COFPROG

Swift: Given a list of integers and a number K, return which contiguous elements of the list sum to K

Return which contiguous elements of the list sum to K in Swift


 Given a list of integers and a number K, return which contiguous elements of the list sum to K.

For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4], since 2 + 3 + 4 = 9.



 func findContiguousElements(lst: [Int], K: Int) -> [Int]? {

        for i in 0..<lst.count {

            for j in i..<lst.count {

                let subList = Array(lst[i...j])

                if subList.reduce(0, +) == K {

                    return subList

                }

            }

        }

        return nil

    }



Previous
Next Post »

BOOK OF THE DAY