# 485. Max Consecutive Ones

### 題目敘述

Given a binary array `nums`, return the maximum number of consecutive `1`'s in the array.

Example 1:

``````Input: nums = [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.
``````

Example 2:

``````Input: nums = [1,0,1,1,0,1]
Output: 2
``````

Constraints:

• `1 <= nums.length <= 105`
• `nums[i]` is either `0` or `1`.

Hint 1:

You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.

### 解法解析

#### 程式範例

##### Python
``````class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
count = 0
result = 0
for num in nums:
if num == 1:
count += 1
result = max(result, count)
else:
count = 0
return result
``````
##### JavaScript
``````/**
* @param {number[]} nums
* @return {number}
*/
var findMaxConsecutiveOnes = function (nums) {
let result = 0;
let count = 0;

for (const num of nums) {
if (num === 1) {
count++;
result = Math.max(result, count);
} else {
count = 0;
}
}
return result;
};
``````
##### Go
``````class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
count = 0
result = 0
for num in nums:
if num == 1:
count += 1
result = max(result, count)
else:
count = 0
return result
``````
##### Swift
``````class Solution {
func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
var result = 0
var count = 0

for num in nums {
if num == 1 {
count += 1
result = max(result, count)
} else {
count = 0
}
}

return result
}
}
``````
##### Kotlin
``````class Solution {
fun findMaxConsecutiveOnes(nums: IntArray): Int {
var result = 0
var count = 0

nums.forEach {
when (it) {
1 -> {
count++
result = Math.max(count, result)
}
else -> count = 0
}
}

return result
}
}
``````