485. Max Consecutive Ones #
Problem #
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
- The input array will only contain
0and1. - The length of input array is a positive integer and will not exceed 10,000
Problem Summary #
Given a binary array, calculate the maximum number of consecutive 1s in it.
Note:
- The input array only contains 0 and 1.
- The length of the input array is a positive integer and will not exceed 10,000.
Solution Approach #
- Given a binary array, calculate the maximum number of consecutive 1s in it.
- Easy problem. Scan the array once, accumulate the count of 1s, dynamically maintain the maximum count, and finally output it.
Code #
package leetcode
func findMaxConsecutiveOnes(nums []int) int {
maxCount, currentCount := 0, 0
for _, v := range nums {
if v == 1 {
currentCount++
} else {
currentCount = 0
}
if currentCount > maxCount {
maxCount = currentCount
}
}
return maxCount
}