Problem: Given an array which only contains 1 and 0, find the maximum number of consecutive 1s in this array.
Example:
Input: [1,0,1,1,0,1] Output: 2
Approach: Nothing to explain. Its a straight forward problem to solve and the approach can be understood easily by just looking at the implementation.
Implementation in C#:
public int FindMaxConsecutiveOnes(int[] nums)
{
int length = nums?.Length ?? 0;
if (length == 0)
{
return 0;
}
int maxCount = 0, currCount = 0;
for (int i = 0; i < length; ++i)
{
if (nums[i] == 1)
{
++currCount;
}
else
{
maxCount = Math.Max(maxCount, currCount);
currCount = 0;
}
}
return Math.Max(maxCount, currCount);
}
Complexity: O(n)
No comments:
Post a Comment