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: Accepted)

#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db;
mt19937 mrand(random_device{}()); 
const ll mod=1000000007;
int rnd(int x) { return mrand() % x;}
ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
// head

const int N=1010000;
int pre[N],maxpre[N],n;
char s[N];

int calc(int x) {
	pre[0]=0;
	rep(i,0,n) {
		if (s[i]=='0'||s[i]=='?') pre[i+1]=pre[i]-1;
		else pre[i+1]=pre[i]+1;
	}
	maxpre[n]=pre[n];
	maxpre[n+1]=-(1<<29);
	per(i,0,n) {
		maxpre[i]=max(maxpre[i+1],pre[i]);
	}
	int cur=0;
	int minpre=0;
	rep(i,0,n) {
		if (s[i]=='0') cur--;
		if (s[i]=='1') cur++;
		if (s[i]=='?') {
			if (cur+1+maxpre[i+1]-pre[i+1]<=x) cur++;
			else cur--;
		}
		minpre=min(minpre,cur);
	}
	return x-minpre;
}

int main() {
	scanf("%s",s);
	n=strlen(s);
	int minp=0,cur=0;
	rep(i,0,n) {
		if (s[i]=='0'||s[i]=='?') --cur; else ++cur;
		minp=max(minp,cur);
	}
	printf("%d\n",min(calc(minp),calc(minp+1)));
}