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;
const int N=1e6+50;
char s[N];int n,now,mn[N],mx[N],m,smx[N],smn[N],ans=1e9,mm;
void solve(int x){
    int dat=mn[1],sum=0;
    for(int i=2;i<=m;i++){
        if(smx[i]+sum+2<=x)sum+=2;
        dat=min(dat,mn[i]+sum);
    }
    ans=min(ans,x-dat);
}
int main(){
    scanf("%s",s+1);n=strlen(s+1);
    for(int i=1,j;i<=n;i++){
        if(s[i]=='?'){m++;mn[m]=mx[m]=now;continue;}
        j=i;
        while(j<n&&s[j+1]!='?')j++;
        m++;mn[m]=now;mx[m]=now;
        for(int k=i;k<=j;k++){
            if(s[k]=='0')now--;
            else now++;
            mn[m]=min(mn[m],now);
            mx[m]=max(mx[m],now);
        }
        i=j+1;
    }
    if(s[n]=='?')m++,mn[m]=mx[m]=now;mm=mx[1];
    for(int i=2;i<=m;i++)mn[i]-=(i-1),mx[i]-=(i-1),mm=max(mm,mx[i]);
    for(int i=1;i<=m;i++)ans=max(ans,mx[i]-mn[i]);
    smx[m]=mx[m];
    for(int i=m-1;i;i--)smx[i]=max(smx[i+1],mx[i]);
    solve(mm);solve(mm+1);cout<<ans;
    return 0;
}