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



Sample input:
6 1
LRLRRL


Sample output:
3

Submission status: Accepted

Solution code:
import sys
#template by uwi 
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces
def convert(ar, st, ed):
    for i in range(st, st + (ed-st+1)//2):
        ar[i], ar[ed-i+st] = not ar[ed-(i-st)], not ar[i]
    if (ed-st+1) % 2 == 1:
        ar[st+(ed-st+1)//2] = not ar[st+(ed-st+1)//2]

n, k = na()
ar = [ True if x == 'R' else False for x in ns()]
st = 1 
ed = 2
#print("checking 0s")
while ed < n-1 and k > 0:
    while st < n and not (ar[st] == False and (st == 0 or ar[st-1] != ar[st])):  
        st += 1
    #st is 0 and one of (st, st-1) is unhappy
    ed = st+1
    while ed < n-1 and not(ar[ed] == False and (ed == n-1 or ar[ed+1] != ar[ed])):
        ed += 1
    if ed >= n-1:
        break
    #print(st, ed)
    #ed is 0 and one of (ed, ed+1) is unhappy
    convert(ar, st, ed)
    k-=1
    st = ed+2
    ed = st+1
#print("checking 1s")
st = 1
ed = 2
while k > 0 and ed < n-1:
    while st < n and not (ar[st] == True and (st == 0 or ar[st-1] != ar[st])):  
        st += 1
    #st is 1 and one of (st, st-1) is unhappy
    ed = st+1
    while ed < n-1 and not(ar[ed] == True and (ed == n-1 or ar[ed+1] != ar[ed])):
        ed += 1
    if ed >= n-1:
        break
    #print(st, ed)
    #ed is 1 and one of (ed, ed+1) is unhappy
    convert(ar, st, ed)
    k -= 1
    st = ed+2
    ed = st+1
#print("checking extremeties 0s")
st = 0
ed = 1
while ed < n and k > 0:
    while st < n and not (ar[st] == False and (st == 0 or ar[st-1] != ar[st])):  
        st += 1
    #st is 0 and one of (st, st-1) is unhappy
    ed = st+1
    while ed < n and not(ar[ed] == False and (ed == n-1 or ar[ed+1] != ar[ed])):
        ed += 1
    if ed >= n:
        break
    #print(st, ed)
    #ed is 0 and one of (ed, ed+1) is unhappy
    convert(ar, st, ed)
    k-=1
    st = ed+2
    ed = st+1
#print("checking extremeties 1s")
st = 0
ed = 1
while k > 0 and ed < n:
    while st < n and not (ar[st] == True and (st == 0 or ar[st-1] != ar[st])):  
        st += 1
    #st is 1 and one of (st, st-1) is unhappy
    ed = st+1
    while ed < n and not(ar[ed] == True and (ed == n-1 or ar[ed+1] != ar[ed])):
        ed += 1
    if ed >= n:
        break
    #print(st, ed)
    #ed is 1 and one of (ed, ed+1) is unhappy
    convert(ar, st, ed)
    k -= 1
    st = ed+2
    ed = st+1

#print(ar)
ans = 0
st = 0
cur = 0
for i in range(n):
    if ar[st] == ar[i]:
        cur += 1
    else:
        ans += cur-1
        cur = 1
        st = i
ans += cur-1 
print(ans)

Submission status: Accepted

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

count=sum(i==0 or S[i-1]!=S[i] for i in range(N))
print(N-max(count-2*K,1))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
group_num = 1
for i in range(1, n):
    group_num += (s[i-1] != s[i])
group_num = max(1, group_num-k*2)

print(n - group_num)

Submission status: Accepted

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

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

Submission status: Accepted

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

ans = 0
flag = 0

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

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

if k > flag//2:
    ans = n-1
elif flag > 1:
    ans += 2*k
else:
    ans += 1

print(ans)

Submission status: Accepted

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

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

if cnt <= k*2:
    ans = n-1
else:
    ans = n-1-(cnt-k*2)

print(ans)

Submission status: Accepted

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

ans = 0
count = k
ans = 0
for i in range(1,n-1):
    if s[i+1] in s[:i] and s[i] != s[i+1] and count > 0:
        count -=1
        j = i
        while s[j] != s[i+1]:
            if s[j] == 'R':
                s = s[:j] + 'L' + s[j+1:]
                j -=1
            elif s[j] == 'L':
                s = s[:j] + 'R' + s[j+1:]
                j-=1

if count > 0 and s != 'L'*n and s != 'R'*n:
    ans += 1

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

print(ans)

Submission status: Accepted

Solution code:
n, k = (int(x) for x in input().split())
s = input()
happy = 0

if(s[0] == 'R' and s[1] == 'R'):
    happy = happy + 1
if(s[n-1] == 'L' and s[n-2] == 'L'):
    happy = happy + 1

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

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

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
s=input()
ans=0
l1=[]
l2=[]
for i in range(N-1):
  if s[i:i+2]=='LR':
    l1.append(i)
  elif s[i:i+2]=='RL':
    l2.append(i)
  elif s[i]=='L' and s[i+1]=='L':
    ans+=1
  elif s[i]=='R' and s[i+1]=='R':
    ans+=1

while K>0 and len(s)-2>ans:
  ans+=2
  K-=1
if len(s)-2<=ans and K>=1:
  ans=len(s)-1
print(ans)

Submission status: Accepted

Solution code:
import re

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

LL = re.finditer('L+', S)
RR = re.finditer('R+', S)

happy = 0
next_happy = []

for l in LL:
    happy += len(l.group(0)) - 1
    if l.regs[0][0] == 0 or l.regs[0][1] == N:
        next_happy.append(1)
    else:
        next_happy.append(2)

for r in RR:
    happy += len(r.group(0)) - 1
    if r.regs[0][0] == 0 or r.regs[0][1] == N:
        next_happy.append(1)
    else:
        next_happy.append(2)

happy += sum(sorted(next_happy, reverse=True)[:K])

if happy >= N:
    happy = N - 1

print(happy)

Submission status: Accepted

Solution code:
tem = list(map(int,input().split()))
n = tem[0]
k = tem[1]
s = [i for i in input()]


count = 0
for i in range(n-1):
    if(s[i]!=s[i+1]):
        count += 1
    else:
        pass

tem_h = n - 1 - count

if((int(count/2)+count%2)>k):
    h = tem_h + 2*k
elif((int(count/2)+count%2)<=k):
    h = n-1

print(h)

Submission status: Accepted

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

def solve():
    global K, S
    concat_S = S[:]
    while 'LL' in concat_S:
        concat_S = concat_S.replace('LL', 'L')
    while 'RR' in concat_S:
        concat_S = concat_S.replace('RR', 'R')

    ans = len(S) - len(concat_S)
    if len(concat_S) >= 4:
        # 2個ずつ消す
        num_rm = min(K, (len(concat_S)-2)//2)
        K -= num_rm
        ans += num_rm * 2
        len_concat_S = len(S) - ans

        if K:
            if len_concat_S == 3:
                ans += 2
            elif len_concat_S == 2:
                ans += 1
        print(ans)
        return
    if K:
        if len(concat_S) == 3:
            ans += 2
        elif len(concat_S) == 2:
            ans += 1
        
    print(ans)
    return

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
S = input()
x = 0
for i in range(N-1):
    if S[i]==S[i+1]:
        x +=1

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

Submission status: Accepted

Solution code:
import numpy as np
N , K = map(int,input().split())
S = list(input())
s = np.ones(N)
for i , st in enumerate(S):
    if st == "R":
        s[i] = -1


s_res =s[1:N] - s[:N-1]

s_abs = np.abs(s_res)

non_happy = s_abs.sum()/2 - 2*K

if non_happy <0:
    non_happy =0

ans = (N-1) - non_happy
print(int(ans))

Submission status: Accepted

Solution code:
"""考え方
ブロックとそのブロック内の人数を調べることで、「現時点での幸福度」を調べる。
一回変換するごとに幸福度が2向上する。

"""

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


before_s = 'a'
cnt_str_cng = 0
ans = 0
for s in S:
  if s == before_s:
    ans += 1
  else:
    cnt_str_cng += 1
  before_s = s

if cnt_str_cng - 1 <= K:
  ans = N - 1
else:
  ans += K * 2

if ans >= N:
  ans = N - 1

print(ans)

Submission status: Accepted

Solution code:
import sys

N,K=map(int,sys.stdin.readline().split())
S=sys.stdin.readline().rstrip()

befores='N'
happiness=0
noCounter=0
for s in S:
  if befores==s:
    happiness+=1
  else:
    noCounter+=1
  befores=s

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

Submission status: Accepted

Solution code:
import copy

words = lambda t : list(map(t, input().split()))
n,k = words(int)
s = input()

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

t = list(copy.copy(s))
x = k
i = 0
while i < len(t) and t[i] == "L":
    i += 1
while x > 0 and i < len(t):
    if t[i] == "L":
        x -= 1
        while i < len(t) and t[i] == "L":
            t[i] = "R"
            i+=1
    else:
        i+= 1

if x > 0 and t[0] == "L":
    i = 0
    while i < len(t) and t[i] == "L":
        t[i] = "R"
        i += 1

#print(t)
def calcAns(t):
    ans = 0
    for i in range(1,len(t)-1):
        #print(t[i])
        if t[i] == "L":
            if t[i-1] == "L":
                ans += 1
        elif t[i] == "R":
            if t[i+1] == "R":
                ans += 1
    if t[0] == "R" and t[1] == "R":
        ans += 1
    if t[-1] == "L" and t[-2] == "L":
        ans += 1
    return ans

ansR = calcAns(t)
#print(ansR)

t = list(copy.copy(s))
x = k
i = 0
while i < len(t) and t[-(i+1)] == "R":
    i += 1

while x > 0 and i < len(t):
    if t[-(i+1)] == "R":
        x -= 1
        while i < len(t) and t[-(i+1)] == "R":
            t[-(i+1)] = "L"
            i+=1
    else:
        i+= 1

if x > 0 and t[-1] == "R":
    i = 0
    while i < len(t) and t[-(i+1)] == "R":
        t[-(i+1)] = "L"
        i += 1

#print(t)
ansL = calcAns(t)
#print(ansL)

print(max(ansL,ansR))

Submission status: Accepted

Solution code:
import copy
# a, b = map(int,input().split())

n,k = map(int,input().split())
# b_l = list(map(int,input().split()))
lr = list(input())

count = 0
sum = 0
lr_org = copy.copy(lr)
if lr[0] == 'L':
        for i in range(n):
                if lr[i] == 'R':
                        lr[i] = 'L'
                        if lr_org[i-1] == 'L':
                                count += 1
                else:
                        if count >= k:
                                break
else:
        for i in range(n):
                if lr[i] == 'L':
                        lr[i] = 'R'
                        if lr_org[i-1] == 'R':
                                count += 1
                else:
                        if count >= k:
                                break
for i in range(n-1):
        if lr[i] == lr[i+1]:
                sum += 1
print(sum)

Submission status: Accepted

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

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

if c % 2 == 0:
    max_K = c // 2
    ans += min(K, max_K) * 2
else:
    max_K = (c - 1) // 2
    ans += min(K, max_K) * 2
    if K > max_K:
        ans += 1
print(ans)

Submission status: Accepted

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

p=0
m=0
r=1
r_list=[]
bit=True
ans=0
if S[0]=="R":
    m+=1
if S[0]=="L":
    p+=1
for i in range(N-1):
    if S[i]=="R" and S[i+1]=="L":
        p+=1
        if bit==True:
            r+=1
    elif S[i]=="L" and S[i+1]=="R":
        m+=1
        if bit==True:
            r+=1
    else:
        r_list.append(r)
        bit=False
        r=0
        ans+=1
if S[N-1]=="R":
    m+=1
    if bit==True:
        r+=1
        r_list.append(r)
if S[N-1]=="L":
    p+=1
    if bit==True:
        r+=1
        r_list.append(r)
t=min(p,m)
ans+=min(t,K)*2

if p+m==2:
    if max(r_list)==p+m:
        if t<=K:
            ans-=1
if p+m==3:
    if max(r_list)==p+m:
        if t<=K:
            ans-=1
if p+m==4:
    if max(r_list)==p+m:
        ans-=1
    if max(r_list)==p+m-1:
        ans-=1

if ans>=N:
    ans=N-1
if ans<0:
    ans=0
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N, K = list(map(int, input().split()))
s = input()
cnt = 0
for be, af in zip(s[:-1], s[1:]):
  if be == af:
    cnt += 1
print(min(cnt + 2*K, N-1))

Submission status: Accepted

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

face = n - 1 - s.count('LR') - s.count('RL')
ans = min(n - 1, face + 2 * k)
print(ans)

Submission status: Accepted

Solution code:
N,K = [int(x) for x in input().split()]
S = list(input())
point = N - 1
count = 0
for i in range(N-1):
    if S[i] != S[i+1]:
        point -= 1
        count += 1
if K >= count/2:
    print(N-1)
elif K >= int(count/2):
    print(N-2)
else:
    print(point+2*K)

Submission status: Accepted

Solution code:
n_k_str = input()
n_k_list = n_k_str.split(" ")
N = int(n_k_list[0])
K = int(n_k_list[1])
S = list(input())

pre_s = S.pop(0)
pre_index = -1
result = 0
for i,s in enumerate(S):
    if s != pre_s:
        temp = i - pre_index - 1
        result += temp
        pre_index = i
    pre_s = s

temp = len(S) - pre_index - 1
result += temp

result += K*2
if result >= N:
    result = N - 1

print(result)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
S=input()
def turn(s):
    if s=="L":
        return("R")
    else:
        return("L")
   
score=0
k_count=0
change_flag=False
S2=list(S)
first_s=S[0]
for i in range(1,N):
    
    if k_count<K:
        if S2[i] != first_s:        
            S2[i]=turn(S2[i])
        if S[i-1]!=S[i] and S[i-1]!=first_s:
            k_count+=1
    if S2[i-1]==S2[i]:
        score+=1
print(score)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import sys,bisect as bs,collections as cl
sys.setrecursionlimit(100000)
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

n,k = m()

a = list(input())
aa = s(a)

al = []
ppp = [0]
ans = sum(map(lambda x:x[1]-1,aa))
for i in range(len(aa)-1):
    ppp.append(ppp[-1]+aa[i][1])

if len(aa) != 1:
    al.append([aa[0][1],0,1])
    al.append([aa[-1][1],len(aa)-1,1])

for i in range(1,len(aa)-1):
    al.append([aa[i][1],i,2])
al.sort(key = lambda x:x[2],reverse = True)
on = [True for i in range(n)]
oon = [0 for i in range(len(aa))]
al = cl.deque(al)
co = min(len(aa),k)
while co:
    if len(al) == 0:
        break
    an = al.popleft()
    co -= 1
    if an[2] == 1:
        if an[1] == 0:
            if not oon[1] == -1:
                oon[0] = -1
                oon[1] = 1
                ans += 1
            else:
                co += 1
        else:
            if not oon[-2] == -1:
                oon[-1] = -1
                oon[-2] = 1
                ans += 1
            else:
                co += 1
    else:
        if not (oon[an[1]-1] == -1 or oon[an[1]+1]):
            oon[an[1]-1] = 1
            oon[an[1]+1] = 1
            oon[an[1]] = -1
            ans += 2
        else:
            co += 1

print(ans)

Submission status: Accepted

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

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

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

Submission status: Accepted

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

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

if hap+2*k >= n-1:
    hap = n-1

else:
    hap = hap + 2*k

print(hap)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = list(input())
count = 0
if N == 1:
    print('0')
    exit()
if S[0] == 'R' and S[1] == 'R':
    count += 1
if S[N - 2] == 'L' and S[N - 1] == 'L':
    count += 1
for i in range(1, N-1):
    if [S[i - 1], S[i]] == ['L', 'L'] or [S[i], S[i + 1]] == ['R', 'R']:
        count += 1
print(str(min(N - 1, count + K * 2)))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = str(input())
check = 0
ans = 0
need_cng = 0
for i in range(0,N-1):
    if (S[i] != S[i+1]):
        check = check +1
if(check%2 ==0):
    need_cng = check/2
else:
    need_cng = check//2+1

if (need_cng > K):
    ans = N - (check - 2*K) -1
else:
    ans = N-1
print(ans)

Submission status: Accepted

Solution code:
N, K = [int(i) for i in input().split(' ')]
s_list = input()

last_s = None
happy = 0
for s in s_list:
    if s == last_s:
        happy += 1
    last_s = s
print(min(happy + 2 * K, N - 1))

Submission status: Accepted

Solution code:
N, K = [int(nk) for nk in input().split()]
S = input()

happy = 0
howmany_LR_or_RL = 0
for i in range(N-1):
  if S[i] == S[i+1]:
    happy += 1
  else: # S[i] != S[i+1]:
    howmany_LR_or_RL += 1

mx_turn =  howmany_LR_or_RL // 2
mx_turn_include_0N = mx_turn + 1
if howmany_LR_or_RL % 2 == 0:
  if K <= mx_turn:
    happy += K * 2
  else: # mx_turn_include_0N <= K:
    happy += (mx_turn_include_0N - 2) * 2
    happy += 2

else: # howmany_LR_or_RL % 2 == 1:
  if K <= mx_turn:
    happy += K * 2
  else: # mx_turn_include_0N <= K:
    happy += mx_turn * 2
    happy += 1

print(happy)

Submission status: Accepted

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

happy = 0

for i in range(N-1):
  happy += (S[i] == S[i+1])

happy += K*2

if happy >= N:
  happy = N-1

print(happy)

Submission status: Accepted

Solution code:
from sys import stdin

N, K = [int(x) for x in stdin.readline().rstrip().split()]
S = stdin.readline().rstrip()

lr = 0
rl = 0
cnt = 0
for i in range(N):
    if i >= 1:
        if S[i] == S[i - 1] == 'L':
            cnt += 1
        if S[i] == 'R' and S[i - 1] == 'L':
            lr += 1
        if S[i] == 'L' and S[i - 1] == 'R':
            rl += 1
    if i <= N - 2:
        if S[i] == S[i + 1] == 'R':
            cnt += 1

op = min(lr, rl, K)
print(cnt + op * 2 + min(max(lr, rl) - op, (K - op)))

Submission status: Accepted

Solution code:
N, K = map(int,input().split())
ans = 0
cnt = 0
s = list(input())
for i in range(N-1):
    if s[i] == s[i+1]:
        ans += 1
    else:
        cnt += 1
if cnt == 1:
    ans = ans + 1
else:
    ans = ans + 2 * min(K,cnt)
print(min(ans,N-1))

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
S = input()
S += '+'
L = []
cur = S[0]
cnt = 1
for i in range(1,n+1):
    if cur == S[i]:
        cnt += 1
    else:
        L.append(cnt)
        cnt = 1
        cur = S[i]
if len(L)%2 == 0:
    if len(L)//2 <= k:
        print(n-1)
    else:
        ans = 0
        for i in range(2*k+1):
            ans += L[i]
        for i in range(2*k+1,len(L)):
            ans += L[i]-1
        print(ans-1)
else:
    if (len(L)-1)//2 <= k:
        print(n-1)
    else:
        ans = 0
        for i in range(2*k+1):
            ans += L[i]
        for i in range(2*k+1,len(L)):
            ans += L[i]-1
        print(ans-1)

Submission status: Accepted

Solution code:
while True:
    try:
        n, k = map(int, input().split())
        if n <= 2:
            print(n-1)
            continue
        lst = []
        ans = 0
        string = input()
        temp = string[0]
        count = 1
        for c in string[1:]:
            if c == temp:
                count += 1
            else:
                temp = c
                lst.append(count)
                ans += count-1
                count = 1
        lst.append(count)
        ans += count-1
        ans += min(k*2, len(lst)-1)
        print(ans)
    except:
        break

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = str(input())
max = N-1
cnt = 0
if N == 1:
    print(0)
    exit()
    
if (S[0] == "R") & (S[1] == "R"):
    cnt += 1
if (S[N-1] =="L") & (S[N-2]=="L"):
    cnt += 1
for i in range(1, N-1):
    if S[i] == "L":
        if S[i-1] == "L":
            cnt += 1
    if S[i] == "R":
        if S[i+1] == "R":
            cnt += 1

if (cnt + K*2) > max:
    print(max)
else:
    print(cnt + K*2)

Submission status: Accepted

Solution code:
import sys
n, k = map(int, input().split())
s = list(input())

if len(s) == 1:
    print(0)
    sys.exit()
ans = 0
for i in range(len(s)-1):
    if s[i] == s[i+1]:
        ans += 1
print(min(len(s)-1, ans+2*k))

Submission status: Accepted

Solution code:
n,k = (int(x) for x in input().split())
s = input()

temp = s[0]
flag = False
count = 0

for i in range(1,len(s)):
    this = s[i]
    if flag == False:
        if not(temp == this):
            flag = True
        else:
            count += 1
    else:
        if not(temp == this):
            if k>0:
                count += 2
                k -= 1
                flag = False
        else:
            count += 1
    
    #print(flag,count,temp,this)
    temp = this
    
    
else:
    if flag == True and k>0:
        count += 1
            
print(count)

Submission status: Accepted

Solution code:
''' بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ '''
#codeforces
gi = lambda : list(map(int,input().split()))
n, m = gi()
s = list(input())
ans = 0
for k in range(1, n):
	if s[k] == s[k - 1]:
		ans += 1
ss = [s[0]]
k = 1
l = [1, 0]
cur = 1
while k < n:
	while k < n and s[k] == s[k - 1]:
		k += 1
	if k == n:
		break;
	l[cur % 2] += 1
	cur += 1
	ss.append(s[k])
	k += 1
x, y = l
x *= 2
y *= 2
x -= 1
if ss[-1] == ss[0]:
	x -= 1
else:
	y -= 1
ans += min(min(x, y), m * 2)
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
s = input()
b = []
shio = 1
for i in range(n):
  if i == n-1:
    b.append(shio)
    break
  if s[i] == s[i+1]:
    shio += 1
    continue
  else:
    b.append(shio)
    shio = 1
ans = 0
for i in b:
  if i >= 2:
    ans += i-1
if (len(b)//2) - k <=0:
  ans = len(s)-1
if (len(b)//2) - k >= 1:
  ans += (k*2)
print(ans)

Submission status: Accepted

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

def change():
    check = S[0]
    k = 1
    while S[k] == check:
        k += 1
    i = 0
    while S[k + i] != check:
        S[k + i] = check
        i += 1

group = 1
old = S[0]
happy_num = 0
for i in range(1, N):
    if old == S[i]:
        group += 1
        if i == N - 1:
            happy_num += group - 1
    else:
        happy_num += group - 1
        old = S[i]
        group = 1
#print(happy_num)


old = S[0]
border = 0
for i in range(1, N):
    if old != S[i]:
        border += 1
        old = S[i]
#print(border)

changed = 2 * K
if changed < border:
    print(happy_num + 2 * K)
else:
    print(N - 1)

Submission status: Accepted

Solution code:
N, K=map(int, input().split())
S=list(input())
SS=[S[0]]

for i in range(1, len(S)):
  if SS[-1]!=S[i]:
    SS.append(S[i])

if len(SS)==1:
  print(N-1)
  exit()
  
if len(SS)==2:
  if K>0:
    print(N-1)
    exit()
  else:
    print(N-2)
    exit()
  
for i in range(1, len(SS)-1):
  if SS[i]!=SS[i-1] and SS[i]!=SS[i+1] and K>0:
    SS[i]=SS[i-1]
    K-=1
  
if SS[0]!=SS[1] and K>0:
  S[0]=S[1]
  K-=1
  
if SS[-1]!=SS[-2] and K>0:
  SS[-1]=SS[-2]
  K-=1
  
unhappy=0
if (SS[0]=='L') or (SS[0]=='R' and SS[1]=='L'):
  unhappy+=1
  
for i in range(1, len(SS)-1):
  if (SS[i]=='L' and SS[i-1]=='R') or (SS[i]=='R' and SS[i+1]=='L'):
    unhappy+=1
    
if (SS[-1]=='R') or (SS[-1]=='L' and SS[-2]=='R'):
  unhappy+=1
  
happy=N-unhappy
print(happy)

Submission status: Accepted

Solution code:
n, B = list(input().split())
n, B=int(n), int(B)
xs =input()
b = None
c = 1
r=0
for x in xs:
    if b==None:
        b=x
        continue
    if x == b:
        c += 1
        continue
    r+=(c-1)
    c = 1
    b=x
r+=(c-1)
print(min(r+(B*2), n-1))

Submission status: Accepted

Solution code:
N, K = list(map(int, input().split()))
S = [1 if x=='R' else -1 for x in input()]
cnt = 0
rule = S[0]
f = False
for i in range(1, N):
    if S[i] != rule:
        f = True
        S[i] *= -1
    else:
        if f:
            f = False
            cnt += 1
    if cnt >= K:
        break

S.insert(0, 1)
S.append(-1)
ans = 0
for i in range(N):
    x = S[i+1]
    y = S[i+1+x]
    if x == y:
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
from collections import deque


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

tmp = deque()
cnt = 1
s += '-'
for i in range(n):
    if s[i] == s[i + 1]:
        cnt += 1
    else:
        tmp.append(cnt)
        cnt = 1

for i in range(k):
    if len(tmp) == 1:
        break
    elif len(tmp) == 2:
        tmp = [tmp[0] + tmp[1]]
    else:
        hoge = tmp[0] + tmp[1] + tmp[2]
        tmp.popleft()
        tmp.popleft()
        tmp.popleft()
        tmp.appendleft(hoge)

if len(tmp) == 1:
    print(tmp[0] - 1)
else:
    total = 0
    for j in tmp:
        if j > 1:
            total += j - 1
    print(total)

Submission status: Accepted

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

l = -1
r = -1

k = 0
while k < K:
    for i in range(1, N):
        #print(i, l, "l")
        if S[i] != S[i-1]:
            if l < 0:
                l = i
            else:
                #print("a", l, i)
                r = i
                for s in range(l, r):
                    if S[s] == "L":
                        S[s] = "R"
                    else:
                        S[s] = "L"
                l = -1
                r = -1
                k += 1
                if k == K:
                    break
    l = -1
    r = -1
    # elif i == N-1 and l >= 0:
    #     for s in range(l, N):
    #         if S[s] == "L":
    #             S[s] = "R"
    #         else:
    #             S[s] = "L"
    #     l = -1
    #     k += 1
    #     if k == K:
    #         break
    if l < 0:
        break
ans = 0
#print(len(set(S)), k, K)
if len(set(S)) == 2 and k < K:
    ans += 1
for i in range(1, N):
    if S[i] == S[i-1]:
        ans += 1
# print(S)
print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
S = input()
fortune = 0
nums = 0
count = 0
for i in range(N):
    if i != N-1 and S[i] == S[i+1]:
        count += 1
    else:
        fortune += count
        count = 0
for i in range(N):
    if i != N-1 and S[i] != S[i+1]:
        nums +=1
if nums%2 ==0 and nums//2 <= K:
    print(fortune + nums)
elif nums%2 == 0 and K <= nums//2:
    print(fortune + K*2)
elif nums%2 ==1 and (nums-1)//2+1 <= K:
    print(fortune + nums)
elif nums%2 ==1 and K <= (nums-1)//2+1:
    print(fortune + K*2)

Submission status: Accepted

Solution code:
N ,K =map(int,input().split())
S ="R" +input() +"L"
coun = 0
foo = 0
for i in range(N+1):
    if S[i:i+2] =="RL":
        coun += 1
        if i==0 or i==N:
            foo  +=1
if K >= coun:
    print(N-1)
elif coun -K <= foo:
    print(N-(coun-K))
else:
    print(N-2*(coun-K) +foo)

Submission status: Accepted

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

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

Submission status: Accepted

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

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

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

Submission status: Accepted

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

leftflag = 0
if s[0] == "L":
  leftflag = 1
  
rightflag = 0
if s[-1] == "R":
  rightflag = 1
    
rlnum = 0

for i in range(len(s)-1):
  if s[i] == "R" and s[i+1] == "L":
    rlnum += 1

rlnum_final = rlnum
rightflag_final = rightflag
leftflag_final = leftflag
    
if k <= rlnum - 1:
  rlnum_final = rlnum - k
  
if k == rlnum :
  rlnum_final = 0
  if rightflag == 0 and leftflag == 0:
    rightflag_final = 1
    
if k >= rlnum + 1:
  rlnum_final = 0
  rightflag_final = 1
  leftflag_final = 0

print(n - (2*rlnum_final + rightflag_final + leftflag_final))

Submission status: Accepted

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

sn = [1]
for i in range(n-1):
  if S[i] == S[i+1]:
    sn[-1] += 1
  else:
    sn.append(1)
    
for i in range(k):
  temp = 0
  if len(sn) > 2:
    for j in range(3):
      temp += sn.pop()
    sn.append(temp)
  elif len(sn) == 2:
    sn[0] += sn.pop()
  else:
    break
    
ans = sum(sn)-len(sn)
print(ans)

Submission status: Accepted

Solution code:
import re

n,k= map(int,(input().split()))
b= input()
LRn=len(re.findall('LR',b))
RLn=len(re.findall('RL',b))

if min(LRn,RLn)>=k:
    ans=k*2
elif min(LRn,RLn)<=k and max(LRn,RLn)>=k:
    ans=k+min(LRn,RLn)
else:
    ans=LRn+RLn

a= list(b)
for i in range(len(a)-1):
    if a[i]==a[i+1]:
        ans +=1

print(ans)

Submission status: Accepted

Solution code:
import sys
inputs = sys.stdin.readlines()

N, K = map(int, inputs[0].split())
S = inputs[1].strip()

from collections import deque

count = 1
A = deque()
for i in range(len(S)):
  try:
    if S[i] == S[i+1]:
      count += 1
    else:
      A.append(count)
      count = 1
  except:
    A.append(count)

for _ in range(K):
  if len(A) >= 3:
    A.append(A.pop() + A.pop() + A.pop())
  elif len(A) == 2:
    A.append(A.pop() + A.pop())
  else:
    break

print(sum(A)-len(A))

Submission status: Accepted

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

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

while count > 0 and K > 0:
    if count == 1:
        count -= 1
        ans += 1
        K -= 1
    else:
        K -= 1
        count -= 2
        ans += 2

print(ans)