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: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect
import heapq

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    

"""
N, X = map(int, input().split())

x = list(map(int, input().split()))

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

# 多次元配列の宣言（あとでintにすること。）（タプルにすること。）
dp = np.zeros((N+1, 4,4,4))
    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

#Distance Transformation
    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)

"""


N, K = list(map(int, input().split()))
S = input()
    
def main():
    res = N
    past = S[0]
    cnt = K
    
# =============================================================================
#     if N == 2:
#         if (S[0] == "R" and S[1] == "L") or (S[0] == "L" and S[1] == "R"):
#             return print(0)
#         if (S[0] == "R" and S[1] == "R") or (S[0] == "L" and S[1] == "L"):
#             return print(1)
#     
# =============================================================================
    for n in range(1, N):
        now = S[n]
        #print(past, now, res)
        if past == "R" and now == "L":
            #print(n, ": BAD")
            res -= 2
            if 0 < cnt:
                #print("reverse")
                res += 2
                cnt -= 1
        past = now
    #print("Reach edge: ", res)
    if S[0] == "L":
        #print(0, ": edge BAD")
        res -= 1
        if 0 < cnt:
            #print("reverse")
            res += 1
            cnt -= 1        
    if S[-1] == "R":
        res -= 1
        #print(N-1, ": edge BAD")
        
    return print(res)
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect
import heapq

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    

"""
N, X = map(int, input().split())

x = list(map(int, input().split()))

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

# 多次元配列の宣言（あとでintにすること。）（タプルにすること。）
dp = np.zeros((N+1, 4,4,4))
    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

#Distance Transformation
    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)

"""


N, K = list(map(int, input().split()))
S = input()
    
def main():
    res = N
    past = S[0]
    cnt = K
    
    if N == 2:
        if (S[0] == "R" and S[1] == "L") or (S[0] == "L" and S[1] == "R"):
            return print(0)
        if (S[0] == "R" and S[1] == "R") or (S[0] == "L" and S[1] == "L"):
            return print(1)
    
    for n in range(1, N):
        now = S[n]
        #print(past, now, res)
        if past == "R" and now == "L":
            #print(n, ": BAD")
            res -= 2
            if 0 < cnt:
                #print("reverse")
                res += 2
                cnt -= 1
        past = now
    #print("Reach edge: ", res)
    if S[0] == "L":
        #print(0, ": edge BAD")
        res -= 1
        if 0 < cnt:
            #print("reverse")
            res += 1
            cnt -= 1        
    if S[-1] == "R":
        res -= 1
        #print(N-1, ": edge BAD")
        
    return print(res)
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

#rの数で幸福な人を最大化する場合
list_R = [""]*len(s)
for n, i in enumerate(s):
    num = 0
    if i == "L":
        for j in range(len(s)-n):
            if s[n+j] == "L":
                num = num + 1
            
            if s[n+j] == "R":
                break
        
    list_R[n] = num

#sを変換する
m = max(list_R) 
s_n = s 
for n, i in enumerate(list_R):
    if i == m:
        break

s_n = s[:n] + "R"*m + s[n+m:]

#スコアリング
score = 0
for n, i in enumerate(s_n[:-1]):
    if s_n[n] == s_n[n+1] and s_n[n] == "R":
        print(s_n[n])
        score = score + 1

print(score)

Submission status: Wrong Answer

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

same = 0
diff = 0
for n in range(N-1):
  if S[n] == S[n+1]:
    same += 1
  else:
    diff += 1

ans = same+min(diff,2*K)
print(ans)

Submission status: Wrong Answer

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

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

aihan = []
ai = 1
han = -1
happi = 0
for i in range(N-1):
    if S[i] == 'R' and S[i+1] == 'L':
        aihan.append(ai)
    elif S[i] == 'L' and S[i+1] == 'R':
        aihan.append(han)
    else:
        aihan.append(happi)

aihan_count = 0

for i, e in enumerate(aihan):
    if K <= 0:
        break
    if e * aihan_count < 0:
        happiness += 2
        K -= 1
    aihan_count += e

if K > 0:
    if aihan_count < 0:
        happiness += 1
        K -= 1

print(happiness)

Submission status: Wrong Answer

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

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

aihan = []
ai = 1
han = -1
happi = 0
for i in range(N-1):
    if S[i] == 'R' and S[i+1] == 'L':
        aihan.append(ai)
    elif S[i] == 'L' and S[i+1] == 'R':
        aihan.append(han)
    else:
        aihan.append(happi)

aihan_count = 0

for i, e in enumerate(aihan):
    if K <= 0:
        break
    if e * aihan_count < 0:
        happiness += 2
        K -= 1
    aihan_count += e

if K > 0:
    if S[0] == 'L' or S[N-1] == 'R':
        if aihan_count < 0:
            happiness += 1
            K -= 1

print(happiness)

Submission status: Wrong Answer

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

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

aihan = []
ai = 1
han = -1
happi = 0
for i in range(N-1):
    if S[i] == 'R' and S[i+1] == 'L':
        aihan.append(ai)
    elif S[i] == 'L' and S[i+1] == 'R':
        aihan.append(han)
    else:
        aihan.append(happi)

aihan_count = 0

for i, e in enumerate(aihan):
    if e * aihan_count < 0:
        happiness += 2
        K -= 1
    aihan_count += e
    if K <= 0:
        break

if K > 0:
    if S[0] == 'L' or S[N-1] == 'R': 
        if aihan_count < 0:
            happiness += 1
            K -= 1

print(happiness)

Submission status: Wrong Answer

Solution code:
N, K = map(int,input().split())
S = input()
group_size = 0
count = 0
for i in range(0,N):
  if i>0 and S[i] == S[i-1]:
    count += 1
  elif i >0 and S[i] != S[i-1]:
    group_size += 1

for i in range(K):
  if group_size > 2:
    count +=2
    group_size -=2
  elif group_size == 2:
    count += 1
    group_size -=1
  else:
    break
print(count)

Submission status: Wrong Answer

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

Llist = []
Rlist = []
now = S[0]
cnt = 0

for i in range(1, N+1):
    if i < N and now == S[i]:
        cnt += 1
    else:
        if now == 'L':
            Llist.append(cnt)
        else:
            Rlist.append(cnt)
        if i < N:
            now = S[i]
            cnt = 0

length = min(len(Llist), len(Rlist))
ans = sum(Llist) + sum(Rlist)
#print(Llist, Rlist, length, ans)
if K == 0:
    print(ans)
else:
    for i in range(min(K, length)):
        length -= 1
        if length == 0 and len(Llist) != len(Rlist):
            ans += 1
        else:
            ans += 2
    print(ans)

Submission status: Wrong Answer

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

Llist = []
Rlist = []
now = S[0]
cnt = 0

for i in range(1, N+1):
    if i < N and now == S[i]:
        cnt += 1
    else:
        if now == 'L':
            Llist.append(cnt)
        else:
            Rlist.append(cnt)
        if i < N:
            now = S[i]
            cnt = 0

length = min(len(Llist), len(Rlist))
ans = sum(Llist) + sum(Rlist)
print(Llist, Rlist, length, ans)
if K == 0:
    print(ans)
else:
    for i in range(min(K, length)):
        length -= 1
        if length == 0 and len(Llist) != len(Rlist):
            ans += 1
        else:
            ans += 2
    print(ans)

Submission status: Wrong Answer

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

Llist = []
Rlist = []
now = S[0]
cnt = 0

for i in range(1, N+1):
    if i < N and now == S[i]:
        cnt += 1
    else:
        if now == 'L':
            Llist.append(cnt)
        else:
            Rlist.append(cnt)
        if i < N:
            now = S[i]
            cnt = 0

length = min(len(Llist), len(Rlist))
ans = sum(Llist) + sum(Rlist)
if K == 0:
    print(ans)
else:
    for i in range(min(K, length)):
        length -= 1
        if length == 0:
            ans += 1
        else:
            ans += 2
    print(ans)

Submission status: Wrong Answer

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

Llist = []
Rlist = []
now = S[0]
cnt = 0

for i in range(1, N+1):
    if i < N and now == S[i]:
        cnt += 1
    else:
        if now == 'L':
            Llist.append(cnt)
        else:
            Rlist.append(cnt)
        if i < N:
            now = S[i]
            cnt = 0

length = min(len(Llist), len(Rlist))
ans = sum(Llist) + sum(Rlist)
for i in range(min(K, length)):
    length -= 1
    if length == 0:
        ans += 1
    else:
        ans += 2

print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
s = list(input())
ss = []
ss.append(s[0])
score = 0
for i in range(1,n):
    if(s[i] != s[i-1]):ss.append(s[i])
    else:score+=1

for i in range(k):
    if(len(ss) >2):
        ss.pop()
        ss.pop()
        score+=2
    else:
        ss.pop()
        score+=1
    if(len(ss) <=1):
        break

print(score)

Submission status: Wrong Answer

Solution code:
# 2019/09/08


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

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

Submission status: Wrong Answer

Solution code:
# 2019/09/08

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

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

Submission status: Wrong Answer

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

x = S.count("RL")
y = int(S[0] == "L" or S[-1] == "R")
    
print(min(N - 1, N - (x * 2 + y) + K * 2))

Submission status: Wrong Answer

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

cnt = sum(S[i] == "R" and S[i + 1] == "L" for i in range(len(S) - 1))
ans = N - (cnt - min(cnt, K)) * 2

if S[0] == "L" or S[-1] == "R":
    ans -= int(S[0] == "L")
    ans -= int(S[-1] == "R")
    if cnt < K:
        ans += 1

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

N,K = II()
S = str(input())

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

n = (count-1)//2
if count%2==1:
    if n+1<=K:
        ans += 2*n+1
    else:
        ans += 2*K
else:
    if n<=K:
        ans += 2*n
    else:
        ans += 2*K

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

N,K = II()
S = str(input())

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

n = (count-1)//2
if count%2==1:
    if n+1<=K:
        ans += 2*n+1
    else:
        ans += 2*K
else:
    if n<=K:
        ans += 2*n
    else:
        ans += 2*K

print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect
import heapq

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    

"""
N, X = map(int, input().split())

x = list(map(int, input().split()))

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

# 多次元配列の宣言（あとでintにすること。）（タプルにすること。）
dp = np.zeros((N+1, 4,4,4))
    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

#Distance Transformation
    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)

"""


N, K = list(map(int, input().split()))
S = input()
    
def main():
    res = N
    past = S[0]
    cnt = K
    
    if N == 2:
        if (S[0] == "R" and S[1] == "L") or (S[0] == "L" and S[1] == "R"):
            return print(0)
        if (S[0] == "R" and S[1] == "R") or (S[0] == "L" and S[1] == "L"):
            return print(1)
    
    for n in range(1, N):
        now = S[n]
        #print(past, now)
        if past == "R" and now == "L":
            #print(n, ": BAD")
            res -= 2
            if 0 < cnt:
                res+= 2
                cnt -= 1
        past = now
    if S[0] == "L":
        #print(0, ": BAD")
        res -= 1
        if 0 < cnt:
            res += 1
            cnt -= 1
    if S[-1] == "R":
        #print(N-1, ": BAD")        
        res -= 1
        if 0 < cnt:
            res += 1
            cnt -= 1
        
        
    return print(res)
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

if N == 1:
    print(0)
else:
    for i in range(N - 1):
        if S[i+1] != S_2[-1]:
            S_2.append(S[i+1])
        if S[i+1] == S[i]:
            ans += 1
    
    num_lr = len(S_2)   # L集合・R集合の数の合計
    num = num_lr // 2   # 便宜的に左端がL集合としたとき、R集合だけを操作できる回数
    
    if num_lr == 1:
        ans = ans
    elif num_lr % 2 == 0:
        if num > K:
            ans += (K * 2)
        elif num <= K:
            ans += ((K * 2) - 1)
    elif num_lr % 2 == 1:
        if num >= K:
            ans += (K * 2)
        elif num < K:
            ans += (num * 2)
    
    print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect
import heapq

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    

"""
N, X = map(int, input().split())

x = list(map(int, input().split()))

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

# 多次元配列の宣言（あとでintにすること。）（タプルにすること。）
dp = np.zeros((N+1, 4,4,4))
    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

#Distance Transformation
    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)

"""


N, K = list(map(int, input().split()))
S = input()
    
def main():
    res = N
    past = S[0]
    cnt = K
    
    if N == 2:
        if S[0] == "R" and S[1] == "L" and S[0] == "L" and S[1] == "R":
            return print(0)
        if S[0] == "R" and S[1] == "R" and S[0] == "L" and S[1] == "L":
            return print(1)
    
    for n in range(1, N):
        now = S[n]
        #print(past, now)
        if past == "R" and now == "L":
            #print(n, ": BAD")
            res -= 2
            if 0 < cnt:
                res+= 2
                cnt -= 1
        past = now
    if S[0] == "L":
        #print(0, ": BAD")
        res -= 1
        if 0 < cnt:
            res += 1
            cnt -= 1
    if S[-1] == "R":
        #print(N-1, ": BAD")        
        res -= 1
        if 0 < cnt:
            res += 1
            cnt -= 1
        
        
    return print(res)
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()