S = gets.chomp counter = Hash.new counter[0] = -1 a_cnt = 0 b_cnt = 0 ans = 0 S.each_char.with_index do |s, i| if s == 'A' a_cnt += 1 else b_cnt += 1 end diff = a_cnt - b_cnt if counter[diff] len = i - counter[diff] ans = len if ans < len else counter[diff] = i end end puts ans