[LeetCode-Eazy] Max Consecutive Ones
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.
找出最大連續 1 的次數在這個陣列
直覺是想計算到底出現幾次並且記錄下來,以及紀錄一個過去出現過的最大累積次數,如果這次的連續次數超過過去的最大次數,就把此次的最大數記為過去累積最大次數。
Golang
func findMaxConsecutiveOnes(nums []int) int {
r := 0
max := r
for i := 0; i < len(nums); i++{
if nums[i] == 1 {
r++
if r > max {
max = r
}
} else {
r = 0
}
}
return max
}