Skip to content

Files

Latest commit

 

History

History
37 lines (32 loc) · 1.03 KB

485.max-consecutive-ones.md

File metadata and controls

37 lines (32 loc) · 1.03 KB

Straightforward

We count the 1 and reset the counter as 0 occurs. And we have to compare with the max count for each iteration.

fun findMaxConsecutiveOnes(nums: IntArray): Int {
    var maxCount = 0
    var currentCount = 0
    for (i in 0 until nums.size) {
        currentCount = if (nums[i] == 1) currentCount + 1 else 0
        maxCount = max(maxCount, currentCount)
    }
    return maxCount
}

X * 0 = 0

It's a binary array, that means the element is either 0 or 1:

  • Every number times zero is zero.
  • Every number times one is itself.
fun findMaxConsecutiveOnes(nums: IntArray): Int {
    var maxCount = 0
    var currentCount = 0
    nums.forEach { i ->
        currentCount = (currentCount + i) * i
        maxCount = max(macCount, currentCount)
    }
    return maxCount
}

Both solutions have the same complexity:

  • Time Complexity: O(n) for only one for-loop.
  • Space Complexity: O(1) for two counters.