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 Rust (1.42.0) (judge verdict: Time Limit Exceeded)

#[macro_use]
mod input_mcr {
    // ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
    // diff: using Parser
    #[macro_export(local_inner_macros)]
    macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

    #[macro_export(local_inner_macros)]
    macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

    #[macro_export(local_inner_macros)]
    macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, char_) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()[0]
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, line) => {
        $parser.next_line()
    };
    ($parser:ident, line_) => {
        $parser.next_line().chars().collect::<Vec<char>>()
    };
    ($parser:ident, i64_) => {
        $parser.fast_i64()
    };
    ($parser:ident, usize_) => {
        $parser.fast_i64() as usize
    };
    ($parser:ident, usize1_) => {
        ($parser.fast_i64() - 1) as usize
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

    use std::io;
    use std::io::BufRead;
    use std::str;

    // ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
    // ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
    // diff: using std::io::BufRead::fill_buf()
    pub struct Parser<R> {
        pub reader: R,
        buf: Vec<u8>,
        pos: usize,
    }

    impl Parser<io::Empty> {
        pub fn from_str(s: &str) -> Parser<io::Empty> {
            Parser {
                reader: io::empty(),
                buf: s.as_bytes().to_vec(),
                pos: 0,
            }
        }
    }

    impl<R: BufRead> Parser<R> {
        pub fn new(reader: R) -> Parser<R> {
            Parser {
                reader: reader,
                buf: vec![],
                pos: 0,
            }
        }
        pub fn update_buf(&mut self) {
            self.buf.clear();
            self.pos = 0;
            loop {
                let (len, complete) = {
                    let buf2 = self.reader.fill_buf().unwrap();
                    self.buf.extend_from_slice(buf2);
                    let len = buf2.len();
                    (len, buf2[len - 1] <= 0x20)
                };
                self.reader.consume(len);
                if complete {
                    break;
                }
            }
        }
        pub fn next<T: str::FromStr>(&mut self) -> Result<T, T::Err> {
            loop {
                let mut begin = self.pos;
                while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                    begin += 1;
                }
                let mut end = begin;
                while end < self.buf.len() && (self.buf[end] > 0x20) {
                    end += 1;
                }
                if begin != self.buf.len() {
                    self.pos = end;
                    return unsafe { str::from_utf8_unchecked(&self.buf[begin..end]) }.parse::<T>();
                } else {
                    self.update_buf();
                }
            }
        }
        pub fn next_line(&mut self) -> String {
            loop {
                let mut begin = self.pos;
                if begin < self.buf.len() && (self.buf[begin] < 0x20) {
                    begin += 1;
                }
                let mut end = begin;
                while end < self.buf.len() && (self.buf[end] >= 0x20) {
                    end += 1;
                }
                if begin != self.buf.len() {
                    self.pos = end;
                    return unsafe { str::from_utf8_unchecked(&self.buf[begin..end]) }.to_string();
                } else {
                    self.update_buf();
                }
            }
        }
        pub fn fast_i64(&mut self) -> i64 {
            loop {
                let mut begin = self.pos;
                while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                    begin += 1;
                }
                if begin == self.buf.len() {
                    self.update_buf();
                    continue;
                }
                let mut res = 0;
                let (is_positive, mut end) = match self.buf[begin] {
                    b'+' => (true, begin + 1),
                    b'-' => (false, begin + 1),
                    _ => (true, begin),
                };
                while end < self.buf.len() && (self.buf[end] > 0x20) {
                    res = res * 10 + (self.buf[end] as i64 - '0' as i64);
                    end += 1;
                }
                if begin != self.buf.len() {
                    self.pos = end;
                    return if is_positive { res } else { -res };
                } else {
                    self.update_buf();
                }
            }
        }
    }
}

use input_mcr::*;
use std::cmp::*;

use std::collections::BTreeMap;

// [upper_limit, lower_limit), [lower, upper), binary step
#[derive(Debug, Clone)]
pub struct LimittedBinStepRange {
    lower: i64,
    upper: i64,
    lower_limit: i64,
    upper_limit: i64,
}

impl LimittedBinStepRange {
    pub fn new(lower: i64, upper: i64, lower_limit: i64, upper_limit: i64) -> LimittedBinStepRange {
        debug_assert!(lower & 1 != upper & 1);
        LimittedBinStepRange {
            lower,
            upper,
            lower_limit,
            upper_limit,
        }
    }
    pub fn fix(&mut self) {
        if self.lower < self.lower_limit {
            self.lower += (self.lower_limit - self.lower + 1) / 2 * 2;
        }
        if self.upper > self.upper_limit {
            self.upper -= (self.upper - self.upper_limit + 1) / 2 * 2;
        }
    }
    pub fn add(&self, x: i64) -> LimittedBinStepRange {
        let mut res = self.clone();
        res.lower += x;
        res.upper += x;
        res.fix();
        res
    }
    pub fn unite(s: LimittedBinStepRange, t: LimittedBinStepRange) -> LimittedBinStepRange {
        debug_assert!(s.lower_limit == t.lower_limit);
        debug_assert!(s.upper_limit == t.upper_limit);
        let mut res = LimittedBinStepRange::new(
            min(s.lower, t.lower),
            max(s.upper, t.upper),
            s.lower_limit,
            s.upper_limit,
        );
        res.fix();
        res
    }
    pub fn is_empty(&self) -> bool {
        !(self.lower < self.upper)
    }
}

fn main() {
    input! {
        s: chars,
    }

    let f = |upper_limit: i64| {
        let mut lower_limit = -((1i64 << 21) - 1);
        'b: for d in (0..21).rev() {
            let t = lower_limit + (1 << d);
            let mut range = LimittedBinStepRange::new(0, 1, t, upper_limit);
            //// eprintln!("range = {:?}", range);
            for &c in &s {
                if c == '0' {
                    range = range.add(1);
                }
                if c == '1' {
                    range = range.add(-1);
                }
                if c == '?' {
                    range = LimittedBinStepRange::unite(range.add(1), range.add(-1));
                }
                //// eprintln!("range = {:?}", range);
                if range.is_empty() {
                    continue 'b;
                }
            }
            //// eprintln!("t = {}, range = {:?}", t, range);
            if !range.is_empty() {
                lower_limit = t;
            }
        }
        //// eprintln!("upper_limit = {}, lower_limit = {}", upper_limit, lower_limit);
        upper_limit - lower_limit
    };

    let mut upper_limit_0 = 1;
    let mut upper_limit_3 = 1i64 << 21;
    let mut memo = BTreeMap::new();
    while upper_limit_3 - upper_limit_0 > 10 {
        let upper_limit_1 = (upper_limit_0 * 2 + upper_limit_3) / 3;
        let upper_limit_2 = (upper_limit_0 + upper_limit_3 * 2) / 3;
        let f_upper_limit_1 = *memo.entry(upper_limit_1).or_insert(f(upper_limit_1));
        let f_upper_limit_2 = *memo.entry(upper_limit_2).or_insert(f(upper_limit_2));
        if f_upper_limit_1 < f_upper_limit_2 {
            upper_limit_3 = upper_limit_2;
        } else {
            upper_limit_0 = upper_limit_1;
        }
    }
    let mut res = 1i64 << 30;
    for i in upper_limit_0..upper_limit_3 + 1 {
        let t = f(i);
        // eprintln!("f({}) = {}", i, t);
        res = min(res, t);
    }
    println!("{}", res - 1);
}