Max Consecutive Ones
Description
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Examples
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 <= 10^5.
nums[i] is either 0 or 1.
Complexity
Time: O(n)
Space: O(1)
Pseudocode
\begin{algorithm}[hbt!]
\caption{Max Consecutive Ones}\label{alg:two}
\LinesNumbered
\KwIn{int\& nums}
\KwOut{int ans}
$count \gets 0$\;
$result \gets 0$\;
$ans \gets 0$\;
$size \gets length(nums)$\;
\eIf{$size == 0$}{
return ans\Comment*[r]{ans = 0}
}
{
$i \gets 0$\;
\While{$i < size$}{
\eIf{nums[i] == 1}{
$count \gets count + 1$\;
}{
$result \gets max(result, count)$\;
$count \gets 0$\;
}
}
$ans \gets max(result, count)$\;
return ans\;
}
\end{algorithm}
Python Solution
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
count = 0
result = 0
size = len(nums)
if nums is None or size == 0:
return 0
# for i in range(0, size):
# if nums[i] == 1:
# count += 1
# else:
# result = max(result, count)
# count = 0
for element in nums:
if element == 1:
count += 1
else:
result = max(result, count)
count = 0
# for index, element in enumerate(nums):
# if element == 1:
# count += 1
# else:
# result = max(result, count)
# count = 0
return max(result, count)
Java Solution
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int result = 0;
int count = 0;
int ans = 0;
int size = nums.length;
if (size == 0)
return ans;
else {
for (int i = 0; i < size; i ++) {
if (nums[i] == 1) {
count ++;
}
else {
result = Math.max(result, count);
count = 0;
}
}
}
ans = Math.max(result, count);
return ans;
}
}
C++ Solution
# include<algorithm>
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int count = 0;
int result = 0;
// int ans = 0;
if (nums.empty())
return 0;
else {
count = 0;
result = 0;
for (int i = 0; i < nums.size(); i++) { // Traversal
if (nums [i] == 1)
count ++;
else {
result = max(result, count);
count = 0;
}
}
// ans = max(result, count);
return max(result, count);
}
}
};
Comments