Algorithm

Problem Name: 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.`

Code Examples

#1 Code Example with Java Programming

```Code - Java Programming```

``````
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int maxCount = 0;
for (int i = 0; i  <  nums.length; ) {
if (nums[i] == 1) {
int currIdx = i;
while (i  <  nums.length && nums[i] == 1) {
i++;
}
maxCount = Math.max(maxCount, i - currIdx);
}
i++;
}
return maxCount;
}
}
``````
Copy The Code &

Input

cmd
nums = [1,1,0,1,1,1]

Output

cmd
3

#2 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
const findMaxConsecutiveOnes = function(nums) {
let sum = 0,
max = 0;

for (let i = 0; i  <  nums.length; i++) {
let temp = sum;
sum += nums[i];
if (temp === sum || i === nums.length - 1) {
max = Math.max(sum, max);
sum = 0;
}
}

return max;
};
``````
Copy The Code &

Input

cmd
nums = [1,1,0,1,1,1]

Output

cmd
3

#3 Code Example with Python Programming

```Code - Python Programming```

``````
class Solution:
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cons=[0,0]
for num in nums:
if num==1:cons[1]+=1
else:cons[1]=0
cons[0]=max(cons[0],cons[1])
return cons[0]

``````
Copy The Code &

Input

cmd
nums = [1,0,1,1,0,1]

Output

cmd
2

#4 Code Example with C# Programming

```Code - C# Programming```

``````
using System;

namespace LeetCode
{
public class _0485_MaxConsecutiveOnes
{
public int FindMaxConsecutiveOnes(int[] nums)
{
int count = 0, maxCount = 0;
foreach (var num in nums)
{
if (num == 0)
{
maxCount = Math.Max(maxCount, count);
count = 0;
}
else
count++;
}

return Math.Max(maxCount, count);
}
}
}
``````
Copy The Code &

Input

cmd
nums = [1,0,1,1,0,1]

Output

cmd
2