Max Consecutive Ones

I’m starting to enjoy binary related problems particularly bit manipulation. But this time, it’s just plain loop that monitors max count of consecutive ones. Easy peasy.

class Solution {
    fun findMaxConsecutiveOnes(nums: IntArray): Int {
        var max = Integer.MIN_VALUE
        var current = 0
        nums.forEach {
            when {
                it == 1 -> current++
                else -> {
                    max = Math.max(current, max)
                    current = 0
                }
            }
        }
        
        return Math.max(max, current)
    }
}
Runtime: 248 ms, faster than 47.37% of Kotlin online submissions for Max Consecutive Ones.
Memory Usage: 37.3 MB, less than 100.00% of Kotlin online submissions for Max Consecutive Ones.
comments powered by Disqus