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:
def main(n,k,s):
  l=[0]
  for i in range(1,n):
    if s[i]==s[i-1]:
      l[-1]+=1
    else:
      l.append(0)
  print(min(n-1,sum(l)+k*2))
    
if __name__=='__main__':
  import sys
  input = sys.stdin.readline
  n,k=map(int,input().split())
  s=input()
  main(n,k,s)

Submission status: Accepted

Solution code:
def main():
    N, K = list(map(int, input().split(' ')))
    S = input()
    char_change_cnt = 0
    before_char = S[0]
    for c in S:
        if before_char == c:
            continue
        before_char = c
        char_change_cnt += 1
    char_change_cnt -= min([char_change_cnt, 2 * K])
    print(N - char_change_cnt - 1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = list(input())
T = []
pre = S[0]
cnt = 0
ans = -1
for i in range(N):
  if S[i] == pre:
    cnt += 1
    pass
  else:
    T += [pre]
    ans += cnt
    cnt = 0
    pre = S[i]

ans += cnt
T += [pre]
ans += min(K*2, len(T)-1)
print(ans)

Submission status: Accepted

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

count = 0
for i in range(1, n+1):
  if s[i] == s[i-1] == "R" or s[i] == s[i+1] == "L":
    count += 1

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

import numpy as np

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

S = np.array(list(input()), dtype='U1')

x = np.count_nonzero(S[1:] == S[:-1])

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

Submission status: Accepted

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

c = 0  #初期状態の幸せな人数
d = 0  #左から見ていって何回向きが変わるか
for i in range(len(S)-1):
    if S[i] == S[i+1]:
        c += 1
    else:
        d += 1

if d >= 2*K:
    print(c+2*K)
else:
    print(c+d)

Submission status: Accepted

Solution code:
# 分からん
n, k = map(int,input().split())
s = input()
 
c = 0
for i in range(1, n):
    if s[i - 1] == s[i]:
        c += 1
  
ans = min(n - 1, c + 2 * k)
print(ans)

Submission status: Accepted

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



happiness=N
for i in range(N):
    if i==0:
        if S[0]=='L':
            happiness-=1
            continue
    if i==N-1:
        if S[N-1]=='R':
            happiness-=1
            continue
    if S[i]=='R':
        if S[i+1]=='L':
            happiness-=1
    else:
        if S[i-1]=='R':
            happiness-=1

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

Submission status: Accepted

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

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

print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

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

fs = 0  #first score
for i in range(n-1):
    if S[i] == S[i + 1]:
        fs += 1
    else:
        pass

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

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
ans=0
bef=s[0]
cnt=0
s2_l=[s[0]]
for i in range(n):
    if bef==s[i]:
        cnt+=1
    else:
        ans+=(cnt-1)
        cnt=1
        bef=s[i]
        s2_l.append(bef)
    if i==n-1:
        ans+=(cnt-1)
s2="".join(s2_l)
n2=len(s2)
if n2==1:
    print(ans)
    exit()
if s2[0]==s2[n2-1]:
    print(ans+min(k,s2.count(s2[1]))*2)
else:
    if k>=n2//2:
        print(ans+n2-1)
    else:
        print(ans+k*2)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
S=input()
Happy=0
for i in range(N):
    if i>0 and S[i-1]==S[i]=='L':
        Happy+=1
    elif i<N-1 and S[i]==S[i+1]=='R':
        Happy+=1
print(min(Happy+2*K,N-1))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
u=s.count('RL')
if u>k:
  print(n-(u-k)*2-(s[0]=='L')-(s[n-1]=='R'))
else:
  print(n-1-(s[0]=='L')*(s[n-1]=='R')*(u==k))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
S=str(input())
section=0
for i in range(N-1):
    if S[i]==S[i+1]:
        continue
    else:
        section+=1
print(N-max(0,section-2*K)-1)

Submission status: Accepted

Solution code:
b=input().split()
K=int(b[1])
a=input()
count=0
for  i in range(len(a)) :
  if i!=len(a)-1 and a[i]=='R' and a[i+1]=='R':
    count+=1
  elif i!=0 and a[i]=='L' and a[i-1]=='L' :
    count+=1
    
for i in range(K) :
  count+=2

if count>=len(a)-1 :
  print(len(a)-1)
else :
  print(count)

Submission status: Accepted

Solution code:
from collections import deque
import numpy as np
N,K = (int(x) for x in input().split())
S = input()
count = []
d = deque(list(S))

now = d.popleft()
cum = 1
for i in range(len(S)-1):
    popped = d.popleft()
    if popped == now:
        cum += 1
    else:
        count.append(cum)
        now = popped
        cum = 1
count.append(cum)
points = [i-1 for i in count]
cs1 = np.array(count).cumsum()
cs2 = np.array(points).cumsum()

if len(count) // 2 <= K:
    print(N-1)
else:
    m = 0
    for i in range(len(count)-2*K):
        if i == 0:
            c = cs1[2*K] - 1
            d = cs2[-1] - cs2[2*K]
        elif i == len(count) - 2*K + 1:
            c = cs1[-1] - cs1[-2*K-2] - 1
            d = cs2[-2*K-2]
        else:
            c = cs1[2*K+i] - cs1[i-1] - 1
            d = cs2[i-1] + (cs2[-1]-cs2[2*K+i])
        m = max(m,c+d)
    print(m)

Submission status: Accepted

Solution code:
n,s=open(0);n,k=map(int,n.split());c=s.count;print(n-1-max(c('LR')+c('RL')-k*2,0))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
c=s.count
print(n-1-max(c('LR')+c('RL')-k*2,0))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
from itertools import*
print(n-max(len(list(groupby(input())))-k*2,1))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
from itertools import *
print(min(n-len(list(groupby(input())))+k*2,n-1))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
t,*s=input()
c=0
for d in s:
  if d==t: c+=1
  t=d
print(min(c+k*2,n-1))

Submission status: Accepted

Solution code:
import re
N, K = map(int, input().split())
S = input()
S = re.sub(r"R+", "R", S)
S = re.sub(r"L+", "L", S)
L_num = S.count("L")
num = min(L_num, N - L_num)

if num <= K:
    print(N - 1)
else:
    print(N - len(S) + 2 * K)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
#from collections import defaultdict
#d = defaultdict(int)
#import fractions
#import math
#import collections
#from collections import deque
#from bisect import bisect_left
#from bisect import insort_left
#N = int(input())
#A = list(map(int,input().split()))
#S = list(input())
#S.remove("\n")
#N,M = map(int,input().split())
#S,T = map(str,input().split())
#A = [int(input()) for _ in range(N)]
#S = [input() for _ in range(N)]
#A = [list(map(int,input().split())) for _ in range(N)]
#import itertools
#import heapq
#import numpy as np
def rle(s):#計算量N
    c = 0
    tmp, count, ans = s[0], 1, []
    for i in range(1,len(s)):
        if tmp == s[i]:
            count += 1
        else:
            ans.append((-1)*count)
            c += count-1
            count = 1
            tmp = s[i]
    if count > 1:
        ans.append(count*(-1))
        c += count-1
    return ans,c #最大2N文字
N,K = map(int,input().split())
S = input()
ans,c = rle(S)
n = len(ans)
import heapq
heapq.heapify(ans)
MIN = min(n,K)
for i in range(MIN):

    a = heapq.heappop(ans)
    c += 2
if c >= N:
    c = N-1
print(c)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
l = sum([i.count('L')-1 for i in s.split('R') if i.count('L') >= 2])
r = sum([i.count('R')-1 for i in s.split('L') if i.count('R') >= 2])
print(min(l+r+2*k, n-1))

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
n, k = [int(i) for i in input().split()]
s = input()
n_group = 0
now = s[0]
cnt = 0
happy = 0
s += 'z'
for i in s:
	if now != i:
		n_group += 1
		if cnt > 1:
			happy += cnt - 1
		cnt = 1
	else:
		cnt += 1
	now = i

for i in range(k):
	if n_group > 2:
		n_group -= 2
		happy += 2
	else:
		happy += 1
if happy > n - 1:
	happy = n - 1
print (happy)

Submission status: Accepted

Solution code:
# LRRRRRRL, LRL は同じ(不幸な人は3人)
# L, R で分割してやると一回の操作でLRL -> LLL -> で不幸な人が2人へる LR の時は LLで1人減る
n, k = list(map(int, input().split(' ')))
s = input()

# LLRRRLL -> 1,1,1に変換して合体させていく
old = ''
converted = []
for c in s:
    if old != c:
        converted.append(1)
        old = c
temp = max(len(converted) - 2*k, 1)  # 必ず一人は犠牲になる
print(n - temp)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
sep = sum(a != b for a, b in zip(s, s[1:]))
print(n - max(0, sep - 2 * k) - 1)

Submission status: Accepted

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

ch_list=[]
for i in range(1,N):
  if S[i-1]!=S[i]:
    ch_list.append(i)
#print(ch_list)
len_ch=len(ch_list)

if len_ch>2*K:
  print(N-1-len_ch+2*K)
else:
  print(N-1)

Submission status: Accepted

Solution code:
import sys
import math  # noqa
import bisect  # noqa
import queue  # noqa


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


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

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

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

res = [0]
for i in range(1, len(s)):
    if s[i] == s[i - 1]:
        res[-1] += 1
    else:
        res.append(0)
print(min(sum(res) + 2 * m, n - 1))

Submission status: Accepted

Solution code:
n,k=list(map(int,input().split()))
s=input()
temp=""
happy=0
zig=0
for i in s:
    if temp==i:
        happy+=1
    else:
        temp=i 
print(n-1 if happy+k*2>=n-1 else happy+k*2)

Submission status: Accepted

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

inside = 0
happy = 0

for i in range(N-1):
    if S[i] == S[i+1]:
        happy += 1
    if S[i] == 'R' and S[i+1] ==  'L':
        inside += 1

happy += 2*(min(K,inside))
if K - inside > 0:
  if S[N-1] == 'R':
    happy += 1
print(happy if happy < N else happy-1)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


def main():
    n, k = map(int, input().split())
    s = list(input())
    cnt = 0  # 幸福の人の数
    for i in range(n-1):
        if s[i] == s[i+1]:
            cnt += 1
    # 1回の操作で最大２人まで幸福にできるが，必ず一人は幸福にならない
    print(min(n-1, cnt + 2 * k))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
def main():
    n, k = map(int, input().split())
    s = list("*" + input() + "*")
    count = 0
    for i in range(1, n + 1):
        if (s[i] == s[i - 1] == "L") or (s[i] == s[i + 1] == "R"):
            count += 1
    print(min(count + 2 * k, n - 1))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()
sys.setrecursionlimit(10**6)

n,k = na()
s = 'p'+ns()+'p'
a = 0

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

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

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
s = input()
flag = [0]*n
f = s[0]
cnt  = 0
for i,t in enumerate(s):
    if t == 'L':
        if i != 0 and s[i-1] == 'L':
            flag[i] = 1
    if t == 'R':
        if i != n-1 and s[i+1] == 'R':
            flag[i] = 1
    if t == f and i != n-1 and s[i+1] != f:
        cnt += 1
ans = sum(flag)
if s[-1] == f:
    ans += min(k,cnt)*2
else:
    ans += 2*cnt - 1 if cnt <= k else 2*k
print(ans)

Submission status: Accepted

Solution code:
import itertools

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

ans=0
for _,l in itertools.groupby(S):
  ans+=len(list(l))-1
ans+=2*K
ans=min(ans,N-1)
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
right = s.count("R")
left = s.count("L")

if min(right, left) <= k:
    print(n-1)
elif n == 1:
    print(0)
else:
    # 操作前の幸福な人の数を調べる
    happy = 0
    for i in range(n-1):
        if s[i] == s[i+1]:
            happy += 1
    #print(happy)
    # RL...LR,LR...RLを数える
    rl = s.count("RL")
    lr = s.count("LR")
    #print(rl, lr)
    min_rllr = min(rl, lr)
    max_rllr = max(rl, lr)
    if rl != 0 and lr != 0:
        if k > min_rllr:
            happy += min_rllr*2 + (max_rllr-min_rllr)
        else:
            happy += k*2
    else:
        happy += k
    print(happy)

Submission status: Accepted

Solution code:
from itertools import*
n, k = map(int, input().split())
print(min(sum(len(list(l))-1 for _, l in groupby(input())) + 2*k, n-1))

Submission status: Accepted

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import numpy as np

def solve(N: int, K: int, S: str):
    S = np.array(([(s=="L")*1 for s in S]))
    dif = S[:-1] - S[1:]
    lr = (dif==1).sum()
    rl = (dif==-1).sum()

    od = 0
    k_ = min(lr,rl) - K
    if lr != rl:
        od = 1

    if k_ + od <= 0:
        print(N-1)
    else:
        print(N-1-k_*2 -od)


    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    S = next(tokens)  # type: str
    solve(N, K, S)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import groupby

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

D = {
    'L': 0,
    'R': 0
}

for val, it in groupby(input()):
    D[val] += 1

u = max([1, D['L'] + D['R'] - 2 * k])

print(n - u)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
r=s.split('L')
r=[i for i in r if i!='']
l=s.split('R')
l=[i for i in l if i!='']
hr=s.count('R')-len(r)
hl=s.count('L')-len(l)
if k>=min(len(r),len(l)):
  print(n-1)
else:
  print(hr+hl+k*2)

Submission status: Accepted

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

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

# L...L|R...R|L...L|...と分解
# 奇数番目をflip
s1 = []
flip_count = 0
for i in range(n):
    if flip_count < k and s[i] == s[0]:
        s1.append('R' if s[0]=='L' else 'L')
    else:
        s1.append(s[i])
    if i < n-1 and s[i] == s[0] and s[i+1] != s[0]:
        flip_count += 1

# 偶数番目をflip
s2 = []
flip_count = 0
for i in range(n):
    if flip_count < k and s[i] != s[0]:
        s2.append('L' if s[0]=='L' else 'R')
    else:
        s2.append(s[i])
    if i < n-1 and s[i] != s[0] and s[i+1] == s[0]:
        flip_count += 1

ans1, ans2 = 0, 0
i = 0
while True:
    if i == 0:
        if s1[i] == 'R' and s1[i+1] == 'R': ans1 += 1
    elif i == n-1:
        if s1[i] == 'L' and s1[i-1] == 'L':
            ans1 += 1
            break
    else:
        if s1[i] == 'R' and s1[i+1] == 'L':
            i += 1
        else:
            ans1 += 1
    i += 1
    if i > n-1:
        break

i = 0
while True:
    if i == 0:
        if s2[i] == 'R' and s2[i+1] == 'R': ans2 += 1
    elif i == n-1:
        if s2[i] == 'L' and s2[i-1] == 'L':
            ans2 += 1
            break
    else:
        if s2[i] == 'R' and s2[i+1] == 'L':
            i += 1
        else:
            ans2 += 1
    i += 1
    if i > n-1:
        break

print(max(ans1, ans2))

Submission status: Accepted

Solution code:
import numpy as np

N, K = input().split(" ")
N, K = int(N), int(K)

S = np.array(list(input()), dtype='U1')
 
x = np.sum(S[1:] == S[:-1])
 
x += 2*K
x = min(x, N-1)
print(x)

Submission status: Accepted

Solution code:
# 初期入力
N,K = (int(x) for x in input().split())
S = input()

#
count_Lr =0 #不幸な人 LR
count_Rl =0 #不幸な人 RL
haji =0
for i in range(N-1):
    s =S[i:i+2]
    if s =="LR":
        count_Lr +=1
    if s =="RL":
        count_Rl +=1
#幸福な人 = 人と人の間の数 -不幸な人
happy_start =len(S) -1 -count_Lr -count_Rl 

change_kanou_num = min(count_Lr,count_Rl,K)
increase = change_kanou_num *2 
if change_kanou_num <K:         #Kが余っていれば、全員同じ向きを向く
    increase += abs(count_Lr -count_Rl)

happy_finsh = happy_start + increase
print(happy_finsh)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
p2=0
p1=0
if n==1:
  print(0)
  exit()
if s[0]=="L":
  p1+=1
if s[n-1]=="R":
  p1+=1
  
for i in range(1,n):
  if not (s[i]=="L" and s[i-1]=="R"):
    continue
  p2+=1
if k<=p2-1:
  print(n-2*p2-p1+2*k)
elif p2-1<k<p2+p1:
  print(n-p1+(k-p2))
else:
  print(n-1)

Submission status: Accepted

Solution code:
# solution
n, m = map(int, input().split())
strs = str(input())
count = 0
for i in range(n):
    if strs[i:i+2] == 'LL' or strs[i:i+2] == 'RR':
        count += 1
print(min((count + 2*m), n-1))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,s=open(0);n,k=map(int,n.split());print(n-max(sum(i!=j for i,j in zip(s,s[1:]))-2*k,1))

Submission status: Accepted

Solution code:
N,K=map(int,input().split());S=input();u=[S[0]]
for c in S:c==u[-1]or u.append(c)
print(len(S)-max(len(u)-2*K,1))

Submission status: Accepted

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


def count_unhappy():
    tcnt = 0
    consecutive = False
    for c in S:
        if c != S[0]:
            consecutive = True
        elif consecutive:
            tcnt += 1
            consecutive = False
    if consecutive:
        tcnt += 1
    unhappy = 2 * tcnt + (0 if S[-1] != S[0] else 1)
    return max(unhappy - 2 * K, 1)


print(N - count_unhappy())

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
assert len(S) == N
first = S[0]
target = "R" if first == "L" else "L"


def count_unhappy():
    tcnt = 0
    consecutive = False
    for c in S:
        if c == target:
            consecutive = True
        elif consecutive:
            tcnt += 1
            consecutive = False
    if consecutive:
        tcnt += 1
    unhappy = 2 * tcnt + (0 if S[-1] == target else 1)
    return max(unhappy - 2 * K, 1)


print(N - count_unhappy())

Submission status: Accepted

Solution code:
# D
n, k = map(int, input().split())
s = list(input())
count = 0
lr = 0
rl = 0
for i in range(n - 1):
    if s[i] == "L":
        if s[i + 1] == "R":
            # LR
            lr += 1
        else:
            # LL 幸せ
            count += 1
    elif s[i + 1] == "L":
        # RL
        rl += 1
    else:
        # RR 幸せ
        count += 1
#LR,RLのどちらかが内側か判定(外側は見ていないので大きいのが内側)
a = max(rl, lr)
#内側の二倍が幸せになる人数
count += 2 * min(k, a)
#幸せになる人はn人にはならないのでn-1と最小をとる
print(min(count,n-1))

Submission status: Accepted

Solution code:
import sys
n,k=map(int,input().split())
s=input()
snum=[]
now_si=""
now_sinum=0
for i in range(len(s)):
    if(now_si!=s[i]):
        now_si=s[i]
        snum.append(now_sinum)
        now_sinum=1
    else:
        now_sinum+=1
else:
    snum.append(now_sinum)
snum.pop(0)

if(len(snum)<3):
    print(sum(snum)-1)
    sys.exit()

for i in range(k):
#    print(snum)
    if(len(snum)<3):
        snum=[sum(snum)]
        break

    snum[-3]+=snum[-2]+snum[-1]
    snum.pop(-1)
    snum.pop(-1)

print(sum(snum)-len(snum))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
S=list(input())
ans=0
lr=0
rl=0
for i in range(N-1):
    if S[i]=="L":
        if S[i+1]=="R":
            lr=lr+1
        else:
            ans=ans+1
    else:
        if S[i+1]=="L":
            rl=rl+1
        else:
            ans=ans+1
change=max(rl,lr)
ans=ans+2*min(change,K)
print(min(ans,N-1))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
#from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
#from math import floor, ceil
#from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
#inf = 10**17
#mod = 10**9 + 7

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
# import math
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product                # product(iter, repeat=n)
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference


def main():
    mod = 1000000007                  # 10^9+7
    inf = float('inf')
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():  return int(input())
    def mi():  return map(int, input().split())
    def mi_0(): return map(lambda x: int(x)-1, input().split())
    def lmi(): return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():  return list(input())
    
    
    n, k = mi()
    L = [elm=='R' for elm in li()]
    seq = [len(list(g)) for _, g in groupby(L)]
    # print(seq)
    x = min(2*k, len(seq)-1)
    print(x + (sum(seq) - len(seq)))
    


if __name__ == "__main__":
    main()

Submission status: Accepted

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

init=0
if s[0] == "L":
    init+=1
if s[-1]=="R":
    init+=1

for i in range(n-1):
    if s[i]=="R" and s[i+1]=="L":
        init+=2

init -= 2*k
if init <= 0:
    init=1
print(n-init)

Submission status: Accepted

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

Submission status: Accepted

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

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

if s[-1] == "R":
    cnt += 1

happy = n - cnt

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

Submission status: Accepted

Solution code:
N,k=map(int,input().split())
A=input()
ans=0
for i in range(0,N):
  if A[i]=='R' and i<N-1:
    if A[i+1]=='R':
      ans=ans+1
  if A[i]=='L' and i>0:
    if A[i-1]=='L':
      ans=ans+1
print(min(N-1,2*k+ans))

Submission status: Accepted

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

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

print(score)

Submission status: Accepted

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

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

print(score)

Submission status: Accepted

Solution code:
n_k = list(map(int,input().split()))
chr_lr = list(input())
cnt_rl = 0
cnt_con = 0

for i in range(n_k[0]-1):
  if(chr_lr[i] == chr_lr[i+1]):
    cnt_con += 1

sum = min(cnt_con + 2*n_k[1],n_k[0]-1)
print(sum)

Submission status: Accepted

Solution code:
def ma():
    return map(int,input().split())

def main():
    n,k=ma()
    b=input()
    left=0
    for i in range(n-1):
        if b[i]==b[i+1]:
            left+=1
    ans=min(left+2*k, n-1)
    print(ans)

if __name__=='__main__':
    main()

Submission status: Accepted

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

press = []
temp = s[0]
cnt = 0
for string in s:
    if temp == string:
        cnt += 1
    else:
        press.append(cnt)
        temp = string
        cnt = 1
press.append(cnt)

if len(press) - 2 * k <= 0:
    print(n-1)
    exit()

ans = 2 * k
for i in press:
    ans += i - 1
print(ans)

Submission status: Accepted

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

cnt = 0
blue = 0
red = 0

for i in range(1, n):
	if s[i] == s[i-1]:
		cnt += 1
	elif s[i-1:i+1] == 'LR':
		blue += 1
	elif s[i-1:i+1] == 'RL':
		red += 1

if k <= min(blue, red):
	cnt += 2 * k
else:
	cnt += 2 * min(blue, red)
	if s[0] == 'R' and s[-1] == 'L':
		cnt += 1
	elif s[0] == 'L' and s[-1] == 'R':
		cnt += 1
	else:
		pass

print(cnt)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
 
happiness = 0
 
for word in S.split("L"):
    happiness += max(0, len(word) - 1)
for word in S.split("R"):
    happiness += max(0, len(word) - 1)
 
res = happiness + 2 * K
print(min(res, N-1))

Submission status: Accepted

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

Submission status: Accepted

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

l = []
bef = ""
start = 0

for i, s in enumerate(S):
    if bef=="":
        start = i
    elif bef!=s:
        l.append(i-start)
        start = i
    bef = s
l.append(i-start+1)

size = len(l)
ans = 0
for i in range(min(2*K+1, size)):
    ans += l[i]
ans -= 1
for i in range(min(2*K+1, size), size):
    ans += l[i]-1
print(ans)

Submission status: Accepted

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

l = []
bef = ""
start = 0

for i, s in enumerate(S):
    if bef=="":
        start = i
    elif bef!=s:
        cnt = 0
        l.append(i-start)
        start = i
    bef = s
l.append(i-start+1)

size = len(l)
ans = 0
for i in range(min(2*K+1, size)):
    ans += l[i]
ans -= 1
for i in range(min(2*K+1, size), size):
    ans += l[i]-1
print(ans)

Submission status: Accepted

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

l = []
bef = ""
start = 0
ans = 0

for i, s in enumerate(S):
    if bef=="":
        start = i
    elif bef!=s:
        cnt = 0
        l.append(i-start)
        start = i
    bef = s
l.append(i-start+1)

size = len(l)
ans = 0
for i in range(min(2*K+1, size)):
    ans += l[i]
ans -= 1
for i in range(min(2*K+1, size), size):
    ans += l[i]-1
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
cnt =0
for i in range(N-1):
    p = S[i]+S[i+1] 
    if p =='RL':
        cnt += 1
cnt2 = 0
if S[0] == 'L':
    cnt2 += 1
if S[-1] == 'R':
    cnt2 += 1
n =N- cnt *2-cnt2
if cnt - 1 >= K:
    print(n+2*K)
elif cnt + cnt2 - 2 >= K:
    print(N-2)
else:
    print(N-1)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
s = input()
ls =[]
p = s[0]
cnt = 1
for i in range(1,n):
    if p != s[i]:
        ls.append((p,cnt))
        cnt = 0
    cnt += 1
    p = s[i]
ls.append((p,cnt))

l = len(ls)
ans = 0
for i in range(k):
    idx = 2*i+1
    if idx >l-1:break
    if idx == l-1:
        ans+=1
        break
    ans +=2
for w,c in ls:
    ans+=c-1
print(ans)