-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathmax_consecutive_ones.cpp
59 lines (52 loc) · 1.34 KB
/
max_consecutive_ones.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
Given a binary array, binary means array's element will be 0 or 1.
find the maximum number of consecutive 1's in this array.
*/
#include <bits/stdc++.h>
using namespace std;
int get_max_consecutive_ones(int ar[] , int N)
{
int max_consecutive_ones = 0 , count_1 = 0;
for(int i = 0; i < N; i++)
{
if(ar[i] == 1)
{
count_1++;
/* here we will keep the maximum value of consecutive
1's */
max_consecutive_ones = max(max_consecutive_ones, count_1);
}
else if(ar[i] == 0)
{
count_1 = 0;
/* as array's element is zero (0)
we will set count_1 as zero */
}
}
return max_consecutive_ones;
}
int main()
{
cout << "Enter the size of the array : \n";
int N;
cin >> N;
int ar[N + 1];
cout << "Enter array elements :\n";
for (int i = 0; i < N; i++)
{
cin >> ar[i];
}
int max_consecutive_ones = get_max_consecutive_ones(ar , N);
cout << "Maximum Consecutive Ones in this array is : ";
cout << max_consecutive_ones << endl;
}
/*
Standard Input and Output
Enter the size of the array :
6
Enter array elements :
1 1 0 1 1 1
Maximum Consecutive Ones in this array is : 3
Time Complexity : O( N )
Space Complexity : O( 1 )
*/