Problem:
Score : 800 points

Problem Statement

Given is a string S, where each character is 0, 1, or ?.

Consider making a string S' by replacing each occurrence of ? with 0 or 1 (we can choose the character for each ? independently).
Let us define the unbalancedness of S' as follows:

(The unbalancedness of S') = \max \{ The absolute difference between the number of occurrences of 0 and 1 between the l-th and r-th character of S (inclusive) :\ 1 \leq l \leq r \leq |S|\}

Find the minimum possible unbalancedness of S'.

Constraints

1 \leq |S| \leq 10^6

Each character of S is 0, 1, or ?.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible unbalancedness of S'.

Sample Input 1

0??

Sample Output 1

1

We can make S'= 010 and achieve the minimum possible unbalancedness of 1.

Sample Input 2

0??0

Sample Output 2

2

Sample Input 3

??00????0??0????0?0??00??1???11?1?1???1?11?111???1

Sample Output 3

4

Solution in C++ (GCC 9.2.1) (judge verdict: Wrong Answer)

#include <bits/stdc++.h>
#define SIZE 1000005
using namespace std;
typedef long long int ll;
typedef pair <int,int> P;

char S[SIZE];
int main()
{
	scanf("%s",&S);
	int n=strlen(S);
	int l=0,r=0;
	int a=0,b=0;
	for(int i=0;i<n;i++)
	{
		if(S[i]=='0')
		{
			a--,b--;
			if(b<l) l=b;
			else if(a<l) a+=2;
		}
		else if(S[i]=='1')
		{
			a++,b++;
			if(r<a) r=a;
			else if(b>r) b-=2;
		}
		else
		{
			if(l==r)
			{
				r++;
				a=b=r;
			}
			else
			{
				a--,b++;
				if(a<l) a+=2;
				if(r<b) b-=2;
			}
		}
	}
	int ret=r-l;
	l=r=0;
	a=b=0;
	for(int i=0;i<n;i++)
	{
		if(S[i]=='0')
		{
			a--,b--;
			if(b<l) l=b;
			else if(a<l) a+=2;
		}
		else if(S[i]=='1')
		{
			a++,b++;
			if(r<a) r=a;
			else if(b>r) b-=2;
		}
		else
		{
			if(l==r)
			{
				l--;
				a=b=l;
			}
			else
			{
				a--,b++;
				if(a<l) a+=2;
				if(r<b) b-=2;
			}
		}
		//printf("%d %d : %d %d\n",l,r,a,b);
	}
	ret=min(ret,r-l);
	printf("%d\n",ret);
}