Problem:
 Score : 400 points    Problem Statement There are N people standing in a queue from west to east.  Given is a string S of length N representing the directions of the people.
The i -th person from the west is facing west if the i -th character of S is L , and east if that character of S is R .  A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.  You can perform the following operation any number of times between 0 and K (inclusive):  Operation: Choose integers l and r such that 1 \leq l \leq r \leq N , and rotate by 180 degrees the part of the queue: the l -th, (l+1) -th, ... , r -th persons. That is, for each i = 0, 1, ..., r-l , the (l + i) -th person from the west will stand the (r - i) -th from the west after the operation, facing east if he/she is facing west now, and vice versa.  What is the maximum possible number of happy people you can have?      Constraints  N is an integer satisfying 1 \leq N \leq 10^5 .  K is an integer satisfying 1 \leq K \leq 10^5 .  |S| = N  Each character of S is L or R .         Input Input is given from Standard Input in the following format:  N  K  S       Output Print the maximum possible number of happy people after at most K operations.        Sample Input 1 6 1
LRLRRL      Sample Output 1 3  If we choose (l, r) = (2, 5) , we have LLLRLL , where the 2 -nd, 3 -rd, and 6 -th persons from the west are happy.       Sample Input 2 13 3
LRRLRLRRLRLLR      Sample Output 2 9       Sample Input 3 10 1
LLLLLRRRRR      Sample Output 3 9       Sample Input 4 9 2
RRRLRLRLL      Sample Output 4 7

Solution (Python):
N, K = map(int, input().split())
S = input()

rights = []
lefts = []

for i in range(N):
    if i == 0:
        if S[i] == "L":
            now = "L"
            start = i
        else:
            now = "R"
            start = i
    else:
        if S[i] != now:
            end = i
            if now == "R":
                rights.append((start, end))
            else:
                lefts.append((start, end))
            start = i
            now = S[i]
            if i == N-1:
                if now == "R":
                    rights.append((i, i+1))
                else:
                    lefts.append((i, i+1))

n_inner_left = 0
n_inner_right = 0
for left in lefts:
    if (0 not in left) and (N not in left):
        n_inner_left += 1
for right in rights:
    if (0 not in right) and (N not in right):
        n_inner_right += 1

total = 0
if S[0] == "L":
    total += 1
if S[N-1] == "R":
    total += 1
for i in range(N-1):
    if S[i] == "R" and S[i+1] == "L":
        total += 2

rest = K
if n_inner_left > n_inner_right:
    reduce_2 = min(K, n_inner_left)
    total -= 2*reduce_2
    rest -= reduce_2
    if S[0] == "L" and rest > 0:
        total -= 1
elif n_inner_left < n_inner_right:
    reduce_2 = min(K, n_inner_right)
    total -= 2*reduce_2
    rest -= reduce_2
    if S[N-1] == "R" and rest > 0:
        total -= 1
else:
    reduce_2 = min(K, n_inner_left)
    total -= 2*reduce_2
    rest -= reduce_2
    if rest > 0:
        if S[0] == "L" and S[N-1] == "R":
            total -= 1
        if S[0] == "R" and S[N-1] == "L":
            total -= 1


print(N-total)

Solution (Python):
N,K=map(int,input().split())
S=input()
S='.'+S
S=S+'.'
P=0
for i in range(N):
  if S[i+1]=='L':
    if S[i]=='L':
      P+=1
  else:
    if S[i+2]=='R':
      P+=1
print(min(N-1,P+K*2))

Solution (Python):
n,k = map(int,input().split())
s = input()

from_start = 0
RtoL = 0
LtoR = 0
for i in range(n-1):
    if s[i] == s[i+1]:
        from_start += 1
    elif s[i] == 'R' and s[i+1] == 'L':
        RtoL += 1
    elif s[i] == 'L' and s[i+1] == 'R':
        LtoR += 1
add = 0
while (RtoL or LtoR) and k:
    k-=1
    if RtoL and LtoR:
        add += 2
        RtoL -= 1
        LtoR -= 1
    elif RtoL:
        add += 1
        RtoL -= 1
    elif LtoR:
        add += 1
        LtoR -= 1
print(from_start+add)

Solution (Python):
n,k=map(int,input().split())
s=input()
t=s[0]
ans=0
u=0
f=True
for i in range(1,n):
    if t==s[i]:
        ans+=1
    else:
        t=s[i]
        if f:
            f=False
        else:
            f=True
            u+=1
if k<=u:
    ans+=2*k
if k>u:
    ans=n-1
print(ans)

Solution (Python):
N,M = list(map(int,input().split()))
S = list(input())

s_=''
S_=[]

if len(set(S))==1:
    ans = len(S)-1
    
else:
    for s in S:
        if s != s_:
            S_.append(s)
            s_=s

        else:
            S_[-1]+=s

    change_str_dict={'R':'L','L':'R'}
    change_str=change_str_dict[S_[1][0]]

    for m in range(1,min(2*M,len(S_)),2):
        S_[m]=change_str*len(S_[m])

    S_=''.join(S_)
    

    s_=S_[0]
    ans=0
    for s in S_[1:]:
        if s == s_:
            ans+=1
        else:
            s_=s

print(ans)

Solution (Python):




def main():
	n , k = map(int, input().split())
	s = input()
	uh=0
	for i in range(0 , len(s)-1):
		if s[i]!=s[i+1]:
			uh=uh+1
	hp = n-1 - max(uh-2*k , 0)
	print(hp)


if __name__=="__main__":
	main()

Solution (Python):


def main():
	n , k = map(int, input().split())
	s = input()
	uh=0
	for i in range(0 , len(s)-1):
		if s[i]!=s[i+1]:
			uh=uh+1
	hp = n-1 - max(uh-2*k , 0)
	print(hp)


if __name__=="__main__":
	main()

Solution (Python):
n, k = map(int, input().split())
s = input()

ans = 0
for i in range(1, n):
    if s[i] == s[i - 1]:
        ans += 1

print(min(ans + 2 * k, n - 1))

Solution (Python):
n, k = list(map(int, input().split()))
s = list(input())

t = [s[0]]

for i in range(1, n):
    if s[i-1] != s[i]:
        t.append(s[i])



a = 0

if len(t) <= 2 * k:
    a = n-1
else:
    a = (n-1) - (len(t) - 1 - 2 * k)

print(a)

Solution (Python):
N, K = map(int, input().split())
S = input()

ans = N - 1
initial = 0
for i in range(N-1):
    if S[i] == S[i+1]: initial += 1
ans = min(ans, initial + 2 * K)
print(ans)

Solution (Python):

def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()

    n, k = map(int, input().split())
    s = input()
    n = len(s)
    ans = 0
    for i in range(n-1):
        if s[i+1] == s[i]:
            ans += 1
    while ans < n-1 and k > 0:
        if n-1-ans > 1:
            ans += 2
        elif n-1-ans == 1:
            ans+=1
        k -=1
    print(ans)
    
    

if __name__ == '__main__':
    main()

Solution (Python):
N, K = map(int, input().split())
S = input()
a = 0
for i in range(N - 1):
    if S[i] != S[i+1]:
        a += 1
ans = N - 1 - max(0, a - (2 * K))
print(ans)

Solution (Python):
n, k = map(int, input().split())
s = input()

ln, rn = 0, 0

i = 0
while i < n:
    if s[i] == 'R':
        while i < n and s[i] == 'R':
            i += 1
        rn += 1
    if i < n and s[i] == 'L':
        while i < n and s[i] == 'L':
            i += 1
        ln += 1
m = min(ln, rn)
if m > k:
    if ln == rn:
        print(n - 2 * (m - k))
    else:
        print(n - 2 * (m - k) - 1)
else:
    print(n - 1)

Solution (Python):
n, k = map(int, input().split())
s = input()

unhappiness = 0
m1, m2 = 0, 0

if s[0] == 'L':
    unhappiness += 1
if s[-1] == 'R':
    unhappiness += 1
i = 0
while i < n and s[i] == 'L':
    i += 1
while i < n:
    h = i
    while i < n and s[i] == 'R':
        i += 1
    if i == n:
        break
    while i < n and s[i] == 'L':
        i += 1
    if h != 0 and i != n:
        m2 += 1
    elif h != 0 or i != n:
        m1 += 1
    unhappiness += 2

if  k <= m2:
    unhappiness -= 2 * k
else:
    unhappiness -= 2 * m2
    k -= m2
    if m1 == 2:
        k -= 1
        unhappiness -= 2
    if k > 0:
        unhappiness = 1
print(n-unhappiness)

Solution (Python):
import copy

n, k =  map(int,input().split())
s = ['R'] + list(input()) + ['L']

cnt = 0
for i in range(1,n+1):
    if s[i] == 'L' and s[i-1] == 'L':
        cnt += 1
    if s[i] == 'R' and s[i+1] == 'R':
        cnt += 1

while k > 0 and cnt < n-1:
    if n- 1 - cnt > 1:
        cnt += 2
    elif n- 1 - cnt > 0:
        cnt += 1
    k -= 1
print(cnt)

Solution (Python):
import copy

n, k =  map(int,input().split())
s = ['R'] + list(input()) + ['L']

cnt = 0
for i in range(1,n+1):
    if s[i] == 'L' and s[i-1] == 'L':
        cnt += 1
    if s[i] == 'R' and s[i+1] == 'R':
        cnt += 1

while k > 0 and cnt < n-1:
    if n- 1 - cnt > 1:
        cnt += 2
    elif n- 1 - cnt > 0:
        cnt += 1
    k -= 1
print(cnt)

Solution (Python):
import sys,math,collections,itertools
input = sys.stdin.readline

N,K=list(map(int,input().split()))
S=input().rstrip()

ori_num=0
turn_num=0
for i in range(N):
    if i>0:
        if S[i-1] =='L' and S[i] =='L':
            ori_num += 1
        if S[i-1] != S[i]:
            turn_num +=1
        
    if i<N-1:
        if S[i] =='R' and S[i+1] =='R':
            ori_num += 1

if turn_num >=2*K:
    ori_num += 2*K
else:
    num = turn_num//2
    num2 = turn_num%2
    ori_num += 2*num+num2
    
print(ori_num)

Solution (Python):
N,K = map(int,input().split())
S = input()

score = 0
for i in range(N-1):
  if S[i] == S[i+1]: score += 1

ans = min(score+2*K, N-1)
print(ans)

Solution (Python):
n, k = map(int, input().split())
target = input('')
target = list(target)
ans = 0
p = 0
for i in range(1, n):
    if target[i-1] != target[i]:
        p += 1
    else:
        ans += 1

print(ans+min(p, k*2))

Solution (Python):
def solve(a,k):
    curr_char = a[0]
    curr_len = 0
    segs = 1
    for x in a:
        if x==curr_char:
            curr_len += 1
        else:
            segs += 1
            curr_len = 1
            curr_char = x
    return len(a)-max(1,segs-2*k)
n,k = map(int,input().split())
print(solve([1 if c=='L' else 0 for c in input()],k))

Solution (Python):
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N, K = LI()
    S = SS()

    
    h = 0
    for i in range(N - 1):
        if S[i] == S[i+1]:
            h += 1

    
    
    cnt = 0
    for i in range(N - 1):
        if S[i] != S[i+1]:
            cnt += 1

    if cnt >= 2 * K:
        h += 2 * K
    else:
        h = N - 1 

    print(h)

if __name__ == '__main__':
    resolve()

Solution (Python):







N, K = map(int, input().split())
S = input()

cnt = 0
for i in range(N - 1):
    if S[i] != S[i + 1]:
        cnt += 1

ans = N - 1 - max(cnt - 2 * K, 0)
print(ans)

Solution (Python):
n,k = list(map(int,input().split()))
s = str(input())
ans = 0
for i in range(1,len(s)):
  if s[i] == s[i-1]:
    ans += 1

if (n-1) >= (ans + 2*k):
  ans += 2*k
else:
  ans = n - 1

print(ans)

Solution (Python):
N, K = map(int, input().split())
S = input().rstrip()

cnt = 0
s0 = "$"
for s in S:
    if s != s0:
        cnt += 1
    s0 = s

print(min(N-cnt+2*K,N-1))

Solution (Python):
N, K = list(map(int, input().split()))
S = str(input())

count = 0
for i in range(N-1):
    if S[i] != S[i+1]:
        count += 1

print(min(N-1, N - 1 - count + K*2))

Solution (Python):
n, k = map(int, input().split())
s = input()
cnt = 0
for i in range(n - 1):
    if s[i] == s[i + 1]:
        cnt += 1
print(min(cnt + 2 * k, n - 1))

Solution (Python):

N, K = map(int, input().split())
S = input()

cnt = S.count("RL")
edge = int(S[0] == "L") + int(S[-1] == "R")

print(min(N - 1, N - 2 * cnt - edge + K * 2))

Solution (Python):
n,k=map(int, input().split())
s=input()

happy=0
for i in range(n-1):
    if s[i]==s[i+1]:
        happy+=1
print(min(happy+k*2, n-1))

Solution (Python):
import sys
from itertools import groupby
def input(): return sys.stdin.readline().rstrip()

def main():
    n,k=map(int, input().split())
    S=list(input())
    p=len(list(groupby(S)))-2*k 
    pp=max(p,1)
    print(n-pp)

if __name__ == '__main__':
    main()

Solution (Python):
n, k = map(int, input().split())
s = list(input())
lr = 0
rl = 0
ans = 0
for i in range(n-1):
    if s[i]=='L' and s[i+1]=='R':
        lr += 1
    elif s[i]=='R' and s[i+1]=='L':
        rl += 1
    else:
        ans += 1

if lr >= k and rl >= k:
    ans += 2*k
elif lr == rl:
    ans += 2*lr
else:
    num = max(lr, rl)
    ans += 2*num-1

print(ans)

Solution (Python):





import math
import fractions
import sys
import bisect
import heapq  
import collections
from collections import Counter
from collections import deque
import pprint
import itertools

sr = lambda: input()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

"""nを素因数分解"""
"""2以上の整数n => [[素因数, 指数], ...]の2次元リスト"""


def factorization(n):
    arr = []
    temp = n
    if n == 1:
        return arr

    for i in range(2, int(-(-n ** 0.5 // 1)) + 1):
        if temp % i == 0:
            cnt = 0
            while temp % i == 0:
                cnt += 1
                temp //= i
            arr.append([i, cnt])

    if temp != 1:
        arr.append([temp, 1])

    if arr == []:
        arr.append([n, 1])

    return arr



def power(a, n, mod):
    x = 1
    while n:
        if n & 1:
            x *= a % mod
        n >>= 1
        a *= a % mod
    return x % mod



def kaijo(n, l, mod):
    if n == 0:
        return 1
    a = n
    tmp = n - 1
    while (tmp >= l):
        a = a * tmp % mod
        tmp -= 1
    return a


class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    divisors.sort()
    return divisors


inf = 10 ** 18
mod = 10 ** 9 + 7

n,k = lr()
s = sr()
rl = 0
default = 0
ret = 0
for i in range(n-1):
    if s[i] == 'R' and s[i+1] == 'L':
        rl += 1
    elif s[i] == s[i+1]:
        default += 1
if rl == 0:
    print(n-1)
else:
    ret = 0
    if s[0] != s[n-1]:
        ret = 1
        if s[n-1] == 'L':
            rl-=1
    ans = default
    ans += 2*min(rl, k)
    if k-rl > 0:
        ans+=ret
    print(ans)

Solution (Python):
n, k = map(int, input().split())
s = list(input())
cnt = 0
tmp = s[0]
t = 0
for i in range(1, n):
    if tmp == s[i]:
        continue
    else:
        cnt += 1
        tmp = s[i]
c = 0
for i in range(1, n):
    if s[i] == s[i-1]:
        c += 1
if cnt <= 2*k:
    print(n-1)
else:
    print(c + 2*k)

Solution (Python):


N, K = (int(i) for i in input().split()) 
S = input()

while "LL" in S:
    S = S.replace("LL", "L")

while "RR" in S:
    S = S.replace("RR", "R")

sad = N - len(S)
sad += K * 2

sad = min(N-1, sad)
print(sad)

Solution (Python):
def count(s):
	c=0
	
	for i in range(len(s)-1):
		if s[i+1] == s[i]:
			c += 1
	return c
	
n, k = map(int, input().split())
s = input()
a = [str(c) for c in s]
cmax = n-1
p = count(a)
while 1:
  if p == cmax:
    break
  elif p == cmax +1:
    p -=1
    break
  elif k > 0:
    p += 2
    k -= 1
  else:
    break
		
print(p)

Solution (Python):
import heapq
t = 1
def max(a,b):
	if a > b:
		return a
	return b
def min(a,b):
	if a < b:
		return a
	return b

while t > 0:
	t -= 1
	n,k = map(int,input().split())
	
	
	
	
	s = input()
	i = 0
	ans = 0
	c = 0
	d = 0
	while(i < n):
		j = i
		
		if s[i] == 'R':
			c += 1
		else:
			d += 1
		while j+1 < n and s[j+1] == s[i]:
			j += 1
		l = j-i+1
		ans += (l-1)
		i = j+1
	c = min(c,d)
	
	if s[0] == s[n-1]:
		if k < c:
			
			ans += 2*k
		else:
			
			ans += 2*(c)
	else:
		if k < c:
			
			ans += 2*k
		else:
			ans += 2*(c-1)
			ans += 1
		
		
	print(ans)

Solution (Python):
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

n, k = MAP()
s = input()
l = s.count('L')

count = 0
for i in range(n):
    if i > 0 and s[i] == s[i-1] == 'L':
        count += 1
    elif i < n - 1 and s[i] == s[i+1] == 'R':
        count += 1

ans = min(count + k*2, n - 1)
print(ans)

Solution (Python):
n,k = map(int,input().split())

s=list(input())

now_happy_count = 0

for i in range(n-1):
    if s[i] == s[i+1]:
        now_happy_count += 1

index = 0

reverse_candidate = []

while index < n:
    if s[index] != s[0]:
        start = index
        while index < n and s[index] != s[0]:
            index += 1
        end = index - 1
        reverse_candidate.append([start, end])
    else:
        index += 1

if len(reverse_candidate) <= k:
    print(n-1)
else:
    print(now_happy_count+2*k)

Solution (Python):
n,k=map(int,input().split())
s=input()
a=[]
cnt=0
flag=s[0]
for i in range(1,n):
  if flag==s[i]:cnt+=1
  else:
    flag=s[i]
    a+=[cnt]
    cnt=0
a+=[cnt]
print(min(sum(a)+2*k,n-1))

Solution (Python):
n,k=map(int,input().split())
s=input()

score=0
for i in range(n-1):
    if s[i]==s[i+1]:
        score+=1
ans=min(score+2*k,n-1)
print(ans)

Solution (Python):
from bisect import bisect

N,K = map(int,input().split())
S = list(input())

f = S[0]

for i in range(N):
  if K == 0:
    break
  if S[i] != f:
    S[i] = f
    for j in range(i+1,N):
      if S[j] == f:
        break
      S[j] = f
    K -= 1
    
i = 0
res = 0

while i < N-1:
  f = S[i]
  for j in range(i+1,N):
    if S[j] != f:
      break
  else:
    res += 1
  res += j-i-1
  i = j
    
print(res)

Solution (Python):
N,K = map(int,input().split())
S = input()

h = 0
for i in range(len(S)-1):
  if S[i] == S[i+1]:
    h += 1
h += 2*K
print(min(N-1, h))

Solution (Python):
N, K = map(int, input().split(' '))
S = input()

groups = 1
for s0, s1 in zip(S, S[1:]):
    if s0 != s1:
        groups += 1

groups = max(1, groups - 2 * K)

print(N - groups)

Solution (Python):
n, k = map(int, input().split())
s = input()

happy = 0
rl = 0
before = s[0]
if before == 'R' and s[1] == 'R':
    happy += 1
for i in range(1, n):
    if before == 'R' and s[i] == 'L':
        rl += 1
    if s[i] == 'L' and s[i-1] == 'L':
        happy += 1
    if i < n-1:
        if s[i] == 'R' and s[i+1] == 'R':
            happy += 1
    before = s[i]

if rl < k:
    print(n-1)
else:
    print(happy + k*2)

Solution (Python):
n, k = map(int, input().split())
s = input()

if n == 1:
    print(0)
    exit()

happy = 0
lchunk, rchunk = [], []
before = s[0]
if before == 'R' and s[1] == 'R':
    happy += 1
for i in range(1, n):
    si = s[i]

    if si != before:
        if before == 'L':
            if lchunk == [] and rchunk == []:
                lchunk.append(1)
            else:
                lchunk.append(2)
        else:
            if rchunk == [] and lchunk == []:
                rchunk.append(1)
            else:
                rchunk.append(2)
    
    if si == 'L' and s[i-1] == 'L':
        happy += 1
    if i < n-1:
        if si == 'R' and s[i+1] == 'R':
            happy += 1
    before = si
if s[-1] == 'L':
    lchunk.append(1)
else:
    rchunk.append(1)

lchunk.sort(reverse=True)
rchunk.sort(reverse=True)

if lchunk == [] or rchunk == []:
    print(happy)
else:
    print(max(happy+sum(lchunk[:k]), happy+sum(rchunk[:k])))

Solution (Python):
def readinput():
    n,k=map(int,input().split())
    s=input()
    return n,k,s

def main(n,k,s):
    nl=s.count('L')
    nr=n-nl
    if nl==0 or nr==0:
        return n-1
    
    c=['L','R']

    
    flip=[]
    happy=0
    if s[0]=='L':
        ci=0
    else:
        ci=1
    l=0
    for i in range(n):
        
        if s[i]==c[ci]:
            l+=1
            
        else:
            
            happy+=max(l-1,0)
            flip.append(ci)
            l=1
            ci=(ci+1)%2
    else:
        happy+=max(l-1,0)
    
    return happy+min(2*k,len(flip))

if __name__=='__main__':
    n,k,s=readinput()
    ans=main(n,k,s)
    print(ans)

Solution (Python):
N,K=map(int,input().split())
S=list(input())

c,s=0,S[0]
for n in S[1:]:
  if s==n:
    c+=1
  s=n

print(min(N-1,c+2*K))

Solution (Python):
N,K = map(int, input().split())
S = input()

A = []
pre = S[0]
cnt = 1
for i in range(1,N):
  if pre == S[i]:
    cnt += 1
  else:
    pre = S[i]
    A.append(cnt)
    cnt = 1
A.append(cnt)
if len(A) == 1:
  print(N-1)
  exit(0)
ans = sum(A) - len(A)

X,Y = [0,0], [0,0]
for i in range(len(A)):
  if i == 0 or i == len(A)-1:
    Y[i%2] += 1
  else:
    X[i%2] += 1
    
wk = [0,0]
for i in range(2):
  if K <=X[i]:
    wk[i] = K * 2
  elif K <= X[i] + Y[i]:
    wk[i] = X[i] * 2 + (K-X[i])
  else:
    wk[i] = X[i] * 2 + Y[i]

print(ans + max(wk))
exit(0)
print(ans, wk)
print(A)
print(X)
print(Y)

Solution (Python):
n,k = map(int,input().split())
s = input()
print(min(sum([1 for i in range(n-1) if s[i] == s[i+1]])+k*2,n-1))

Solution (Python):
n, k = map(int, input().split())
s = input()
ans = 0
for i in range(1,n):
    if s[i] == s[i-1]:
        ans += 1
ans += 2 * k
if ans >= n:
    ans = n-1
print(ans)

Solution (Python):
N, K = map(int, input().split())
S = input()
RL = 0
for i in range(N - 1):
    if S[i] == 'R' and S[i + 1] == 'L':
        RL += 1
egde = (S[0] == 'L') + (S[-1] == 'R')
if K >= RL:
    K -= RL
    RL = 0
    if K > 0:
        egde = max(1, egde - K)
else:
    RL -= K
print(N  - 2 * RL - egde)

Solution (Python):

import sys
import re
from collections import deque, defaultdict
from itertools import combinations, combinations_with_replacement
import bisect
from math import factorial, sqrt, log, ceil, floor
sys.setrecursionlimit(1000000)


def solve(S, N, K, LR):
    happy = 0
    one = 0
    two = 0
    prev = None
    for i in range(N+1):
        s = S[i]
        if prev is None:
            prev = (s, i)
            continue

        if prev[0] == s:
            continue

        happy += (i - 1) - prev[1]
        if prev[0] == LR:
            if prev[1] == 0 and i - 1 == N - 1:
                pass
            elif prev[1] == 0 or i - 1 == N - 1:
                one += 1
            else:
                two += 1
        prev = (s, i)

    spans = [2] * two + [1] * one
    if spans:
        happy += sum(spans[:min(K, len(spans))])

    return happy


def main():
    input = sys.stdin.readline
    
    
    

    N, K = map(int, input().split())
    S = input().strip()

    S += 'D'  

    happy = max([solve(S, N, K, 'L'), solve(S, N, K, 'R')])
    print(happy)


if __name__ == '__main__':
    main()

Solution (Python):
n, k = map(int, input().split())
s = input()
score = 0
for i in range(1, len(s)):
    if s[i - 1] == s[i]:
        score += 1

ans = min(n - 1, score + 2 * k)

print(ans)

Solution (Python):
import sys 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N, K = map(int, readline().split())
S = readline().decode().rstrip()
cnt = 1
for i in range(N-1):
    if S[i] != S[i+1]:
        cnt += 1 
print(min(N-1,N-cnt+2*K))

Solution (Python):
n, k = map(int, input().split())
S = input()
h = 0
for i in range(1,n):
    if S[i]==S[i-1]:
        h += 1
print(min(h+2*k, n-1))

Solution (Python):
import sys
input=sys.stdin.readline

N,K=(int(x) for x in input().rstrip('\n').split())
L = list(input())
now = L[0]
same = 0
for x in L[1:]:
  if x == now:
    same += 1
  else:
    now = x
res = same + K*2
if res > N-1:
  res = N-1
print(res)

Solution (Python):
import sys
from io import StringIO
import unittest
import os


sys.setrecursionlimit(999999999)



def resolve(test_def_name=""):
    
    n, k = map(int, input().split())
    s_s = list(input())

    if len(s_s) == 1:
        print(0)
        return

    
    target = []
    actcnt = 0
    for cnt, s in enumerate(s_s[1:], start=1):
        if actcnt == k:
            break
        bef_str = s_s[cnt - 1]

        if bef_str != s:
            target.append(cnt)
        if len(target) == 2:
            for work in range(target[0], target[1]):
                s_s[work] = "L" if s_s[work] == "R" else "R"
            target = []
            actcnt += 1
        if len(target) == 1 and cnt == len(s_s) - 1:
            for work in range(target[0], len(s_s)):
                s_s[work] = "L" if s_s[work] == "R" else "R"

    
    ans = 0
    for cnt, s in enumerate(s_s[1:], start=1):
        bef_str = s_s[cnt - 1]
        if bef_str == s:
            ans += 1

    print(ans)



class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve(sys._getframe().f_back.f_code.co_name)
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """6 1
LRLRRL"""
        output = """3"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """13 3
LRRLRLRRLRLLR"""
        output = """9"""
        self.assertIO(test_input, output)

    def test_input_3(self):
        test_input = """10 1
LLLLLRRRRR"""
        output = """9"""
        self.assertIO(test_input, output)

    def test_input_4(self):
        test_input = """9 2
RRRLRLRLL"""
        output = """7"""
        self.assertIO(test_input, output)

    def test_input_5(self):
        test_input = """1 2
R"""
        output = """0"""
        self.assertIO(test_input, output)

    def test_input_6(self):
        test_input = """10 2
LLLLLRLRLL"""
        output = """9"""
        self.assertIO(test_input, output)

    def test_input_7(self):
        test_input = """10 2
LLLLLRLRLR"""
        output = """8"""
        self.assertIO(test_input, output)

    def test_input_8(self):
        test_input = """10 1
RLLLLRLRLR"""
        output = """5"""
        self.assertIO(test_input, output)

    def test_input_9(self):
        test_input = """10 1000
LLLLLRLRLL"""
        output = """9"""
        self.assertIO(test_input, output)

    def test_input_9(self):
        test_input = """10 1000
LLLLLLLLLL"""
        output = """9"""
        self.assertIO(test_input, output)

    def test_input_10(self):
        test_input = """10 1
RLLLRLLLLR"""
        output = """7"""
        self.assertIO(test_input, output)

        test_input = """10 2
RLRLRLRLRL"""
        output = """4"""
        self.assertIO(test_input, output)

        test_input = """10 3
RLRLRLRLRL"""
        output = """6"""
        self.assertIO(test_input, output)

        test_input = """10 4
RLRLRLRLRL"""
        output = """8"""
        self.assertIO(test_input, output)

        test_input = """10 5
RLRLRLRLRL"""
        output = """9"""
        self.assertIO(test_input, output)

    
    def test_input_11(self):
        test_input = """10 5
RLRLRLRLRL"""
        output = """9"""
        self.assertIO(test_input, output)



if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        
        resolve()

    else:
        
        unittest.main()

Solution (Python):







__giturl__ = "$URL$"


from sys import stdin
input = stdin.readline


def main():
  N, K = list(map(int, input().split()))
  A = input()[:-1]

  origin = 0
  for i in range(N-1):
    if A[i] == A[i+1]:
      origin += 1

  if A[0] == 'L':
    target = 'R'
  else:
    target = 'L'

  if A[-1] == 'L':
    A += 'R'
  else:
    A += 'L'

  lim = K
  pre = A[0]
  for i in range(1, N+1):
    
    
    
    
    
    

    if (not(pre == A[i]) and not(A[i] == target)):
      lim -= 1
      if i == N:
        origin += 1
      else:
        origin += 2
      if lim <= 0:
        break
    pre = A[i]

  print(origin)


if(__name__ == '__main__'):
  main()

Solution (Python):
def resolve():
    N, K = list(map(int, input().split()))
    S = list(input())
    base = 0
    prev = S[0]
    for i in range(1, N):
        if prev == S[i]:
            base += 1
        prev = S[i]
    
    print(min(base+2*K, N-1))


if '__main__' == __name__:
    resolve()

Solution (Python):
N,K=map(int,input().split())
S=input()
if N == 1:
  print(0)
  exit()
if N == 2:
  if K>=1:
    print(1)
  else:
    print(0)
    exit()


ans = 0
d = 0
for i,s in enumerate(S[:-1]):
  if S[i] == S[i+1]:
    ans += 1

ans += 2*K
print(min(ans,N-1))

Solution (Python):
n, k = map(int, input().split())
s=input()
ans = 0
for i, j in zip(s[:-1], s[1:]):
  if i+j == "LL" or i+j == "RR":
    ans += 1
print(min(n-1, ans + 2*k))

Solution (Python):
n, k = map(int, input().split())
s = input()
a = 'A'
cnt = 0
for i in s:
  if a != i:
    a = i
    cnt += 1
print(n-max(1,cnt-2*k))

Solution (Python):


def main():
    from itertools import tee

    N, K = map(int, input().split())
    S = input()

    s1, s2 = tee(S, 2)
    next(s2)

    cnt = 0
    for c1, c2 in zip(s1, s2):
        if c1 != c2:
            cnt += 1

    ans = N - 1 - max(cnt - K * 2, 0)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))

n,k=nii()
s=input()

happy=0
unhappy=0
for i in range(1,n):
  if s[i-1]==s[i]:
    happy+=1
  else:
    unhappy+=1

for i in range(k):
  if unhappy==1:
    happy+=1
    break
  happy+=2
  unhappy-=2

print(min(happy,n-1))

Solution (Python):
N, K = map(int,input().split())
S = input()


cnt = 1

for i in range(N-1):
    if S[i] != S[i+1]:
        cnt += 1

print(N - max(1, cnt - 2*K))

Solution (Python):



from fractions import gcd
from itertools import combinations,permutations,accumulate 

from collections import deque,defaultdict,Counter
import decimal
import re











import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
n,k = readInts()
S = input()
a = 0
for i in range(1,len(S)):
    if S[i] != S[i-1]:
        a += 1
print(n - 1 - max(a - 2 * k, 0))