Changes in a string

4.1

66 votes
Algorithms, Greedy Algorithms, LOOP construct, String Manipulation
Problem

You are given a string S of N characters comprising of As and Bs. You can choose any index i and change Si to either A or B.

Find the minimum number of changes that you must make to string S such that the resulting string is of the following format:

 AAAA........x number of AsBBBB........nx number of Bs       

where 0xn

In other words, your task is to determine the minimum number of changes such that string S has x number of As in the beginning, followed by the remaining (nx) number of Bs.

Input format

  • First line: A single integer T denoting the number of test cases
  • For each test case:
    • First line contains a single integer N denoting the size of the string
    • Second line contains string S

Output format

For each test case, print a single line containing one integer that represents the minimum number of changes you need to make in string S as mentioned in the question.

Constraints

1T1041N106

Note: Sum of N overall test cases does not exceed 5×106

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

For the string AAB we don't need to make any changes.

For the string AABAA we can change B to A and get the string in the required form.

For the string B we don't need to make any changes.

For the string BABA we need to make atleast 2 changes to get the string in required form. One possible way is AABB

Editor Image

?