Fast maximum consecutive positive numbers

How to calculate maximum consecutive positive numbers using closures?

var numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
//in this case it should be 3

print(numbers.reduce(0, { $1 > 0 ? $0 + 1 : $0 } ))//this counts total positive numbers
+4
source share
4 answers

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()!

.

+6
var currentResult = 0
var maxResult = 0
for i in numbers {
    currentResult = i > 0 ? currentResult + 1 : 0
    if maxResult < currentResult {
       maxResult = currentResult
    }
}
print(maxResult)

+2
var numbers = [1, 3, 4, -1, -2, 5, 2, -2, -3, -4, 5]

let result = numbers.reduce((current: 0, max: 0)) { result, number in
    var value = result

    if number > 0 {
        value.current += 1
        value.max = max(value.current, value.max)
    } else {
        value.current = 0
    }

    return value
}



result.max
+2
source

Generating subsequences:

let numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
let subsequences: [[Int]] = numbers.reduce(into: []) { (result, number) in
    guard
        var currentSequence = result.last,
        let lastNumber = currentSequence.last
    else {
        result = [[number]]
        return
    }

    if number == lastNumber + 1 {
        currentSequence.append(number)
        result.removeLast()
        result.append(currentSequence)
    } else {
        result.append([number])
    }
}
let longest = subsequences.max { $0.count < $1.count }
print(subsequences)
print("Longest subsequence: \(longest)")
print("Longest length: \(longest?.count)")
+1
source

Source: https://habr.com/ru/post/1688805/


All Articles