Alternating String

 A binary string is called alternating if no two adjacent characters of the string are equal. Formally, a binary string 

of length is called alternating if for each

.

For example, 0, 1, 01, 10, 101, 010, 1010 are alternating strings while 11, 001, 1110 are not.

You are given a binary string

of length . You would like to rearrange the characters of such that the length of the longest alternating substring of

is maximum. Find this maximum value.

A binary string is a string that consists of characters 0 and 1. A string

is a substring of a string if can be obtained from

by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Input Format

  • The first line of input contains an integer
, denoting the number of test cases. The
  • test cases then follow:
  • The first line of each test case contains an integer
  • .
  • The second line of each test case contains the binary string
    • .

    Output Format

    For each test case, output the maximum possible length of the longest alternating substring of

    after rearrangement.

    Constraints

  • contains only the characters 0 and 1.
  • Sum of
  • over all test cases does not exceed
    • .

    Sample Input 1

    4
    3
    110
    4
    1010
    4
    0000
    7
    1101101
    

    Sample Output 1

    3
    4
    1
    5
    

    Explanation

    Test case

    : Swapping the second and third characters makes . Hence the length of the longest alternating substring is

    (choosing the entire string as a substring).

    Test case

    : The given string is an alternating string of length

    .

    Test case

    : The length of the longest alternating substring is for any rearrangement of

    .

    Test case

    : One possible rearrangement of is , which has an alternating substring of length (the substring starting at index and ending at index ). 
    Previous
    Next Post »