Update: simplified solution: divide the array into pieces of positive elements and determine the maximum slice length:
let numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
let maxConsecutive = numbers.split(whereSeparator: { $0 <= 0 }).map { $0.count }.max()!
print(maxConsecutive) // 3
Old answer :) Using ideas from Swift running :
let numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
let maxConsecutive = numbers.map({
() -> (Int) -> Int in var c = 0; return { c = $0 > 0 ? c + 1 : 0; return c }
}()).max()!
It map()
maps each element of the array to a counter of consecutive positive numbers to the position of the elements, in this case
[1, 2, 3, 0, 0, 1, 2, 0, 0, 0, 1]
"
" c
,
. c
,
.
,
let maxConsecutive = numbers.lazy.map( ... ).max()!
.