Problem: Find the Maximum Consecutive One's in Array
Given a binary array consists of 0's and 1's. Find the maximum number of consecutive 1's in that Array.
Ex: Array A=[1,1,0,0,1,1,1,0,0,1,1,1,1]
Above array contains
2 - consecutive 1's
3 - consecutive 1's
and
4 - consecutive 1's
the maximum value among 2, 3, 4 is 4.
The output for the problem is 4.
Solution to find the Maximum Consecutive 1's in Array
{tab title="Java" class="green"}
class Programming9{
public int maxConsecutiveOnes(int[] nums) {
int maxvalue=0, count=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==1){
count++;
maxvalue=Math.max(maxvalue,count);
}
else
count=0;
}
return maxvalue;
}
}
{tab title="C++" class="orange"}
class Programming9{
public:
int maxConsecutiveOnes(vector<int>& nums) {
int count=0,result=0;
int n=nums.size();
for(int i=0;i<n;i++){
if(nums[i]==1){
count++;
result=max(count,result);
}
else
count=0;
}
return result;
}
};
{tab title="Python" class="blue"}
class Programming9:
def maxConsecutiveOnes(self, nums: List[int]) -> int:
maxvalue=0
count=0
for i in range(len(nums)):
if nums[i]==1:
count=count+1
maxvalue=max(count, maxvalue)
else:
count=0
return maxvalue
{/tabs}
It is really a beginners code, we can even further reduce it.
Optimized Java Solution to find the Maximum Consecutive 1's in Array
class Programming9{
public int maxConsecutiveOnes(int[] nums) {
int maxvalue=0, count=0;
for(int i:nums)
maxvalue = Math.max(maxvalue, count= i==1 ? count+1: 0);
return maxvalue;
}
}
The loop should repeat N number of times to explore all values in an Array, so the time complexity is O(n)
.