def max(a,b); a > b ? a : b; end S = gets.chomp M = { 0 => 0 } d = 0 S.chars.each.with_index(1).inject(0) do |s,(c,i)| s += (c == 'A' ? 1 : -1) if M[s] d = max(d, i - M[s]) else M[s] = i end s end puts d