Maximum consecutive 1s

PHOTO EMBED

Mon Feb 07 2022 12:42:53 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #lecture #arrays #maximumconsecutive1s #consecutiveones #count

// Efficient Method : Time Complexity : O(n), Auxiliary space : O(1)

import java.util.*;
import java.io.*;

class GFG 
{ 
    static int maxConsecutiveOnes(int arr[], int n)
    {
    	int res = 0, curr = 0;

    	for(int i = 0; i < n; i++)
    	{
    		if(arr[i] == 0)
    			curr = 0;
    		else
    		{
    			curr++;

    			res = Math.max(res, curr);
    		}
    	}
    	
    	return res;
    }

    public static void main(String args[]) 
    { 
       int arr[] = {0, 1, 1, 0, 1, 1, 1}, n = 7;

       System.out.println(maxConsecutiveOnes(arr, n)); // Output : 3
    } 
}


// Naive Method : Time Complexity : O(n^2), Auxiliary space : O(1)

    static int maxConsecutiveOnes(int arr[], int n)
    {
    	int res = 0;

    	for(int i = 0; i < n; i++)
    	{
    		int curr = 0;

    		for(int j = i; j < n; j++)
    		{
    			if(arr[j] == 1) curr++;
    			else break;
    		}

    		res = Math.max(res, curr);
    	}
    	
    	return res;
    }
content_copyCOPY

Find count of maximum consecutive 1s in a binary array.