a = gets.chomp max_length = 0 (0..a.length).each do |i| descend_str, ascend_str = a[0, i-1].to_s, a[i-1, a.length].to_s balanced_length = descend_str.length if descend_str.count('A') == descend_str.count('B') max_length = balanced_length if ((balanced_length || 0) >= max_length) balanced_length = ascend_str.length if ascend_str.count('A') == ascend_str.count('B') max_length = balanced_length if ((balanced_length || 0) >= max_length) end puts max_length