#include <bits/stdc++.h>
using namespace std;
#define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);
using ll = long long;
int main() {
FAST;
int tc = 1, ti;
cin >> tc;
for (ti = 1; ti <= tc; ++ti) {
ll n, k, i, l, r, ans;
string s;
cin >> n >> k;
cin >> s;
s = " " + s;
vector<ll> pa(n+1, 0), pb(n+1, 0), pq(n+1, 0);
for (i = 1; i <= n; ++i) {
pa[i] = pa[i-1];
pb[i] = pb[i-1];
pq[i] = pq[i-1];
if (s[i] == 'A') pa[i] += 1;
else if (s[i] == 'B') pb[i] += 1;
else if (s[i] == '?') pq[i] += 1;
}
k = min(k, pq[n]);
auto get_ans = [&](ll i, ll qa, ll qb) -> ll {
// all '?' in s[1...i] = 'a'
// all '?' in s[i+1...n] = 'b'
ll curr = 0;
// a -> b
l = pa[i];
r = pb[n] - pb[i];
curr += l*r;
// a -> ?
l = pa[i];
r = min(qb, pq[n] - pq[i]);
curr += l*r;
// ? -> b
l = min(qa, pq[i]);
r = pb[n] - pb[i];
curr += l*r;
// ? -> ?
l = min(qa, pq[i]);
r = min(qb, pq[n] - pq[i]);
curr += l*r;
return curr;
};
ans = 0;
for (i = 1; i <= n; ++i) {
ans = max(ans, get_ans(i, k/2, k-k/2));
ans = max(ans, get_ans(i, (k+1)/2, k-(k+1)/2));
}
cout << ans << "\n";
}
return 0;
}