Maximal Continuous Rest
Hazrat Ali
Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,an (each ai is either 0 or 1), where ai=0 if Polycarp works during the i-th hour of the day and ai=1 if Polycarp rests during the i-th hour of the day.
Days go one after another endlessly and Polycarp uses the same schedule for each day.
What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.
The first line contains n (1≤n≤2⋅105) — number of hours per day.
The second line contains n integer numbers a1,a2,…,an (0≤ai≤1), where ai=0 if the i-th hour in a day is working and ai=1 if the i-th hour is resting. It is guaranteed that ai=0 for at least one i.
Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.
5 1 0 1 0 1
2
6 0 1 0 1 1 0
2
7 1 0 1 1 1 0 1
3
3 0 0 0
0
Solution
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
int front = 0;
for (int i = 0; i < n; i++)
{
if (a[i] == 1)
{
front++;
}
else
{
break;
}
}
int back = 0;
for (int i = n - 1; i > -1; i--)
{
if (a[i] == 1)
{
back++;
}
else
{
break;
}
}
int ans = 0, cnt = 0;
for (int i = 0; i < n; i++)
{
if (a[i] == 1)
{
cnt++;
}
else
{
cnt = 0;
}
ans = max(ans, cnt);
}
cout << max(ans, front + back) << endl;
return 0;
}