#C13703. Longest Balanced Substring

    ID: 43271 Type: Default 1000ms 256MiB

Longest Balanced Substring

Longest Balanced Substring

Given a string consisting only of the characters 'a' and 'b', find the length of the longest contiguous substring in which the number of 'a's is equal to the number of 'b's. In other words, if we denote the number of 'a's by \(n_a\) and the number of 'b's by \(n_b\), you need to find the maximum length of a substring such that \(n_a = n_b\).

Example:

  • For the input string "aababbab", the longest balanced substring is "aababbab" which has length 8.
  • For the input string "aaaa", there is no contiguous substring where the numbers of 'a's and 'b's are equal, so the answer is 0.

Your task is to implement an efficient solution that reads a single string from standard input and prints the length of the longest balanced substring to standard output.

inputFormat

The input contains a single line string consisting only of the characters 'a' and 'b'.

For example:

aababbab

outputFormat

Output a single integer representing the length of the longest contiguous substring where the number of 'a's and 'b's are equal.

For example:

8
## sample
aababbab
8