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:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

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

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

    return arr

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret


# ここから書き始める
n, k = map(int, input().split())
s = input()

x = []
l = 0
r = 0
for i in range(n):
    if i == 0:
        if s[i] == "L":
            l += 1
        else:
            r += 1
    elif s[i] == s[i - 1]:
        if s[i] == "L":
            l += 1
        else:
            r += 1
    else:
        if s[i] == "L":
            x.append(["R", r])
            r = 0
            l = 1
        else:
            x.append(["L", l])
            l = 0
            r = 1
if l > 0:
    x.append(["L", l])
else:
    x.append(["R", r])

# print(x)
ans = 0
for i in range(n):
    if s[i] == "L":
        if i != 0 and s[i - 1] == "L":
            ans += 1
    elif i != n - 1 and s[i + 1] == "R":
        ans += 1

m = len(x)
if m > 1:
    left = [] 
    right = [] 
    for i in range(m):
        if i == 0:
            if x[i][0] == "L":
                left.append(1)
            else:
                right.append(2)
        elif i == m - 1:
            if x[i][0] == "L":
                left.append(2)
            else:
                right.append(1)
        else:
            if x[i][0] == "L":
                left.append(2)
            else:
                right.append(1)
    left.sort(reverse=True)
    right.sort(reverse=True)
    # print("left =", left)
    # print("right =", right)
    ans += max(sum(left[:k]), sum(right[:k]))
# print("ans =", ans)
print(ans)

Submission status: Wrong Answer

Solution code:
def evaluate(directions):
    ans = 0
    for i, d in enumerate(directions):
        if 0 <= i+d and i+d <= N-1:
            if directions[i] == directions[i+d]:
                ans += 1
    return ans

def find_lr(directions):
    N = len(directions)
    for i in range(1, N):
        if directions[i-1] != directions[i]:
            l = i
            break
    else:
        l = None
        return None, None
    
    for i in range(l+1, N):
        if directions[i-1] != directions[i]:
            r = i
            break
    else:
        r = N - 1
    return l, r

def solve(directions):
    l, r = find_lr(directions)
    if l is None:
        return False
    else:
        if l is not None:
            for i in range(l, r):
                directions[i] *= -1
        return True 
    
N, K = map(int, input().split())
S = input()
directions = [1 if s=="R" else -1 for s in S]
for k in range(K):
    result = solve(directions)
    if result == False:
        break
    
print(evaluate(directions))

Submission status: Wrong Answer

Solution code:
def evaluate(directions):
    ans = 0
    for i, d in enumerate(directions):
        if 0 <= i+d and i+d <= N-1:
            if directions[i] == directions[i+d]:
                ans += 1
    return ans

def find_lr(directions):
    N = len(directions)
    for i in range(1, N):
        if directions[i-1] != directions[i]:
            l = i
            break
    else:
        l = None
        return None, None
    
    for i in range(l+1, N):
        if directions[i-1] != directions[i]:
            r = i
            break
    else:
        r = N - 1
    return l, r

def solve(directions):
    l, r = find_lr(directions)
    if l is None:
        return False
    else:
        if l is not None:
            for i in range(l, r+1):
                directions[i] *= -1
        return True 
    
N, K = map(int, input().split())
S = input()
directions = [1 if s=="R" else -1 for s in S]
for k in range(K):
    result = solve(directions)
    if result == False:
        break
    
print(evaluate(directions))

Submission status: Wrong Answer

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

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

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

print(happy)

Submission status: Wrong Answer

Solution code:
import numpy as np

N, K = map(int, input().split())
S = np.array(list(input()))
S = (S == 'L') * 1
inner01 = 0
outer10 = 0
happy = 0
for i in range(N - 1):
    if S[i] == S[i + 1]:
        happy += 1
    elif S[i] - S[i + 1] == 1:
        outer10 += 1
    else:
        inner01 += 1
up = min(inner01, min(K, outer10))
happy += 2 * up
if K - up >= 1 and outer10 - up >= 1 and S[0] == 1:
    happy += 1
if K - up >= 2 and outer10 - up >= 2 and S[-1] == 0:
    happy += 1

print(happy)

Submission status: Wrong Answer

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

C = []

count = 0
dotti = S[0]
ans = 0

for i in range(n):
    if dotti != S[i]:
        count += 1
        dotti = S[i]
    if S[i] == "R" and i < n-1: 
        if S[i+1] == "R":
            ans += 1
    elif S[i] == "L" and i > 0: 
        if S[i-1] == "L":
            ans += 1

while k > 0:
    if count >= 2:
        ans += 2
        count -= 2
    else:
        ans += 1
        break
    k -= 1

print(ans)

Submission status: Wrong Answer

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

C = []

count = 0
dotti = S[0]
ans = 0

for i in range(n):
    if dotti != S[i]:
        count += 1
        dotti = S[i]
    if S[i] == "R" and i < n-1: 
        if S[i+1] == "R":
            ans += 1
    elif S[i] == "L" and i > 0: 
        if S[i-1] == "L":
            ans += 1

while k > 0:
    if count >= 2:
        ans += 2
        count -= 1
    else:
        ans += 1
        break
    k -= 1

print(ans)

Submission status: Wrong Answer

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

C = []

count = 0
dotti = S[0]
ans = 0

for i in range(n):
    if dotti != S[i]:
        count += 1
        dotti = S[i]
    if S[i] == "R" and i < n-1: 
        if S[i+1] == "R":
            ans += 1
    elif S[i] == "L" and i > 0: 
        if S[i-1] == "L":
            ans += 1

while k > 0:
    if count > 2:
        ans += 2
        count -= 1
    else:
        ans += 1
        break
    k -= 1

print(ans)

Submission status: Wrong Answer

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

C = []

count = 0
dotti = S[0]
ans = 0

for i in range(n):
    if dotti != S[i]:
        count += 1
    if S[i] == "R" and i < n-1: 
        if S[i+1] == "R":
            ans += 1
    elif S[i] == "L" and i > 0: 
        if S[i-1] == "L":
            ans += 1

while k > 0:
    if count > 2:
        ans += 2
        count -= 1
    elif count == 2:
        ans += 1
        break
    k -= 1

print(ans)

Submission status: Wrong Answer

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

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

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

l_cnt=[]
for i in range(n):
  if s[i]=='R':
    if i==0:
      if s[i+1]=='L':
        l_cnt.append(1)
    if i==n-1:
      if s[i-1]=='L':
        l_cnt.append(1)
    else:
      t_l_cnt=s[i-1:i+2].count('L')
      l_cnt.append(t_l_cnt)

r_cnt=[]
for i in range(n):
  if s[i]=='L':
    if i==0:
      if s[i+1]=='R':
        r_cnt.append(1)
    if i==n-1:
      if s[i-1]=='R':
        r_cnt.append(1)
    else:
      t_r_cnt=s[i-1:i+2].count('R')
      r_cnt.append(t_r_cnt)

ans=l_cnt+r_cnt
ans.sort(reverse=True)
ans=sum(ans[:k])

print(happy+ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right

def main():
    N, K = map(int, input().split())
    S = input()
    ans = 0# 初期幸福な人数
    for i in range(N-1):
        if S[i] == S[i+1]:
            ans += 1
    M = []# 'RL'の位置を格納
    if S[0] == 'L':
        M.append(1)
        # ans -= 1
    for i in range(1,N-1):
        if S[i:i+2] == 'RL':
            M.append(2)
            # ans -= 2
    if S[N-1] == 'R':
        M.append(1)
        # ans -= 2
    M.sort(reverse=True)
    # print(M,ans)
    print(ans + sum(M[:K]))
    

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
s = list(input())
c = 0
a = 0
	
for i in range(n-1):
	if s[i] == s[i+1]:
		c += 1
	if a < k:
		if s[i] == 'R' and s[i+1] == 'L':
			c += 2
			a += 1
if a < k and a + 2 <= k:
	if s[0] == 'L':
		c += 1
	if s[-1] == 'R':
		c += 1
if a < k and a + 1 >= k:
	if s[0] == 'L' or s[-1] == 'R':
		c += 1
print(c)

Submission status: Wrong Answer

Solution code:
import itertools

def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]

def main():
    N, K = ZZ()
    S = input()
    gr = itertools.groupby(S)
    ll = []
    for c, d in gr: ll.append([c, len(list(d))])

    output = N - len(ll)
    i = 1
    for _ in range(K):
        if i < len(ll): output += 2
        else: break
        i += 2

    print(output)

    return

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
print("a")

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
input = lambda: sys.stdin.readline().rstrip()
INF = 10**9 + 1


def solve():
    N, K = map(int, input().split())
    S = np.array(list(input()), dtype='str')

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

    ri = INF
    kc = 0
    fr = S[0] == 'R'

    for i in range(N):
        if S[i] == 'R':
            ri = min(ri, i)
        if ri != INF and S[i] == 'L':
            if fr:
                fr = False
                fr_1 = ri
                fr_2 = i
                ri = INF
                continue
            S[ri:i] = 'L'
            ri = INF
            kc += 1
            if kc == K:
                break
    else:
        if ri != INF and S[-1] == 'R':
            S[ri:N] = 'L'
            kc += 1
        if kc < K:
            if S[0] == 'R' and (not fr):
                S[fr_1:fr_2] = 'L'

    # print(S)

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

    print(happy)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import sys

input = lambda: sys.stdin.readline().rstrip()


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

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

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

    if count <= K:
        if count == 0:
            if S[0] == 'L' and S[-1] == 'R':
                inc = 1
            else:
                inc = 0
        if count == 1:
            inc = 1
        elif count >= 2:
            inc = (count - 1) * 2 + 1
    elif count > K:
        inc = K * 2

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

    ans = happy + inc
    #print(happy, count, inc)
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import sys

input = lambda: sys.stdin.readline().rstrip()


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

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

    count = 0
    if S[0] == 'L':
        count += 1
    if S[-1] == 'R':
        count += 1

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

    if count <= K:
        if count == 1:
            inc = 0
        elif count == 2:
            inc = 1
        elif count >= 3:
            inc = (count - 2) * 2 + 1
    elif count > K:
        if count == 1:
            inc = 0
        elif count == 2:
            inc = 1
        elif count >= 3:
            if count + 2 >= K:
                inc = K * 2
            elif count + 1 == K:
                inc = (K - 1) * 2 + 1

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

    ans = happy + inc
    #print(happy, count, inc)
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import sys

input = lambda: sys.stdin.readline().rstrip()


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

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

    edge = 0
    if S[0] == 'L' and S[-1] == 'R':
        edge = 1

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

    if count == 0:
        inc = edge
    elif count < K:
        inc = count * 2 + edge
    elif count >= K:
        inc = K * 2

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

    ans = happy + inc
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import sys

input = lambda: sys.stdin.readline().rstrip()


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

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

    edge = 0
    if S[0] == 'L' and S[-1] == 'R':
        edge = 1

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

    if count == 0:
        inc = edge
    elif count <= K:
        inc = count * 2
    elif count > K:
        inc = K * 2 + edge

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

    ans = happy + inc
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import sys

input = lambda: sys.stdin.readline().rstrip()


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

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

    edge = 0
    if S[0] == 'L' and S[-1] == 'R':
        edge = 1

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

    if count == 0:
        inc = edge
    elif count < K:
        inc = count * 2
    elif count >= K:
        inc = K * 2

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

    ans = happy + inc
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
s = list(input())
c = 0
a = 0
for i in range(n-1):
	if s[i] == s[i+1]:
		c += 1
i = 0
if s[-1] == 'R':
	s.append('L')
else:
	s.append('R')

while a < k and len(s) >= 2:
	if s[0] != s[1] and s[-1] != s[-2] and s[0] == s[-1]:
		c += 2
		a += 1
	s = s[1:]

	i += 1
print(c)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
s = list(input())
c = 0
a = 0
for i in range(n-1):
	if s[i] == s[i+1]:
		c += 1
i = 0
if s[-1] == 'R':
	s.append('L')
else:
	s.append('R')
print(s)
while a < k and len(s) >= 2:
	if s[0] != s[1] and s[-1] != s[-2] and s[0] == s[-1]:
		c += 2
		a += 1
	s = s[1:]

	i += 1
print(c)

Submission status: Wrong Answer

Solution code:
N,K=map(int, input().split())
S=input()
comp=[]
tmp=""

for i in range(N):
  if tmp=="":
    tmp=S[i]
    cnt=1
  else:
    if S[i]==tmp:
      cnt +=1
      
  if S[i]!=tmp:
    comp.append([tmp,cnt])
    tmp=S[i]
    cnt=1
  if i==N-1:
    comp.append([tmp,cnt])
  
ans=0  
for run in comp:
  ans += run[1]-1
ans += K*2
ans = min(ans,N)
print(ans)

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

Solution code:
n,k = map(int, raw_input().split())
s = raw_input()
cd = 0
d = None
for l in s:
	if d != l:
		cd +=1
		d = l
score = 0
for u,v in zip(s,s[1:]):
	if u == v:
		score +=1



if cd > 2:
	t = min(k,(cd - 2))
	k -= t
	score += 2 * t 
	cd -= 2 * t
if cd == 2 and k:
	score +=1
	cd -= 1
print score

Submission status: Wrong Answer

Solution code:
n,k = map(int, raw_input().split())
s = raw_input()
cd = 0
d = None
for l in s:
	if d != l:
		cd +=1
		d = l
score = 0
for u,v in zip(s,s[1:]):
	if u == v:
		score +=1

if cd > 2:
	score += (cd - 2) * 2
	cd = 2
if cd == 2:
	score +=1
print score

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())

def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())

def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def SI(): return input().split()

def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))
INF = float('inf')

from math import ceil, floor, log2
from collections import deque
from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product


def solve():
    n, k = MI()

    S = list(input())

    A = []
    # print(S)
    cnt = 0
    pre = ''
    for s in S:
        if pre == s:
            cnt += 1
        else:
            if cnt:
                A.append((pre, cnt))
            pre = s
            cnt = 1
    if cnt:
        A.append((pre, cnt))
    # print('A', A)

    target = 'L'
    rev = 'R'
    ans = 0
    for _ in range(2):
        B = A.copy()
        T = []
        for idx, (b, cnt) in enumerate(B):
            if b == target:
                l = 0
                r = 0
                if idx - 1 >= 0:
                    l = B[idx-1][1]
                if idx + 1 < len(B):
                    r = B[idx+1][1]

                T.append((idx, l + cnt + r, cnt))

        T = sorted(T, key=lambda x: x[1], reverse=True)
        # print('T', T)

        q = deque(T)
        for _ in range(k):
            if len(q) > 0:
                idx, _, cnt = q.popleft()
                B[idx] = (rev, cnt)

        res = 0
        sm = 0
        pre = ''
        for (b, cnt) in B:
            if pre == b:
                sm += cnt
            else:
                if sm > 1:
                    res += sm - 1
                sm = cnt
                pre = b
        if sm > 1:
            res += sm - 1

        # print('B', B)
        # print(res)
        ans = max(res, ans)
        target = 'R'
        rev = 'L'
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
N,K=map(int, input().split())
S=input()
comp=[]
tmp=""

for i in range(N):
  if tmp=="":
    tmp=S[i]
    cnt=1
  else:
    if S[i]==tmp:
      cnt +=1
      
  if S[i]!=tmp:
    comp.append([tmp,cnt])
    tmp=S[i]
    cnt=1
  if i==N-1:
    comp.append([tmp,cnt])
    
print(comp)    
for _ in range(K):
  if len(comp)<=3:
    print(N-1)
    exit()
  else:
    c= [comp[j][1]+comp[j+2][1] for j in range(len(comp)-2)]
    print(c)
    maxi=max(c)
    idx = c.index(maxi)
    s= comp[idx][1]
    t = comp[idx+2][1]
    if idx>=1:
      comp[idx-1][1] += t
    if idx+3<len(comp):
      comp[idx+3][1] += s
    if comp[idx+1][0]=="R":
      comp[idx+1][0]="L"
    else:
      comp[idx+1][0]="R"
    comp = comp[:idx] + [comp[idx+1]]+comp[idx+3:]
      
  print(comp)

ans=0  
for a in comp:
  ans += a[1]-1
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    from itertools import groupby
    n, k = map(int, input().split())
    s = input()
    tmp = 0
    grp = 0
    m = ''
    for v, g in groupby(s):
        gr = len(list(g))
        tmp += gr - 1
        grp += 1
        m += v

    for s, t, v in [('LRL', 'LLL', 2), ('RLR', 'RRR', 2), ('LR', 'RR', 1), ('RL', 'LL', 1)]:
        u = m.count(s)
        tmp += v * min(u, k)
        k = max(0, k - u)
        m.replace(s, t)

    print(tmp)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    from itertools import groupby
    n, k = map(int, input().split())
    s = input()
    tmp = 0
    grp = 0
    m = ''
    for v, g in groupby(s):
        gr = len(list(g))
        tmp += gr - 1
        grp += 1
        m += v

    for s, t, v in [('LRL', 'LLL', 2), ('RLR', 'RRR', 2), ('RL', 'RR', 1), ('LR', 'LL', 1)]:
        u = m.count(s)
        tmp += v * min(u, k)
        k = max(0, k - u)
        m.replace(s, t)

    print(tmp)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

B = input()
happy = 0
for i in range(n):
  if B[i]=="L" and i != 0 :
    if B[i-1] == "L":
      happy +=1
  if B[i]=="R" and i != n-1 :
    if B[i-1] == "R":
      happy +=1
print(min(happy+2*k, n-1))

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
S=input()
c=0
d=0
for i in range(n-1):
    if S[i]==S[i+1]:
        c+=1
    if S[i]!=S[i+1]:
        d+=1
print(c+2*d-1 if (d<=k and S[0]!=S[-1]) else c+2*min(d,k))

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
S=input()
c=0
d=0
for i in range(n-1):
    if S[i]==S[i+1]:
        c+=1
    if S[i]!=S[i+1]:
        d+=1

print(c+2*d-1 if (d<=k and S[0]!=S[-1]) else c+2*k)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
S=input()
c=0
d=0
for i in range(n-1):
    if S[i]==S[i+1]:
        c+=1
    if S[i]!=S[i+1]:
        d+=1
print(c+2*k-1 if (d<=k and S[0]!=S[-1]) else c+2*k)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
S=input()+'X'
c=0
d=0
for i in range(n):
    if S[i]==S[i+1]:
        c+=1
    if S[i]!=S[i+1]:
        d+=1
print(c+2*k if d>k else c+2*k-1)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
S=input()
c=0
d=0
for i in range(n-1):
    if S[i]==S[i+1]:
        c+=1
    if S[i]!=S[i+1]:
        d+=1
print(c+2*k if d>k else c+2*k-1)

Submission status: Wrong Answer

Solution code:
N, K = [int(_c) for _c in input().split(" ")]
S_orig = input()
point_list = []
for target, non_target in zip(["L", "R"], ["R", "L"]):
    S = list(S_orig)

    start_idx_list = []
    before_char = None
    for i, c in enumerate(S):
        if i == 0:
            start_idx_list.append(i)
            before_char = c
        else:
            if before_char == non_target and c == target:
                start_idx_list.append(i)
            before_char = c
    
    if len(start_idx_list) - 1 >= K:
        point_list.append(len(start_idx_list) - 1)
        continue
        
    longest = 0
    start_idx = -1
    end_idx = -1
    for i in range(len(start_idx_list) - K):
        cur_length = start_idx_list[i + K] - start_idx_list[i] + 1
        if cur_length > longest:
            start_idx = start_idx_list[i]
            end_idx = start_idx_list[i + K]
            longest = cur_length

    for _idx in range(start_idx, end_idx):
        S[_idx] = target
    S = ["N"] + S + ["N"]

    point = 0
    for idx in range(1, N + 1):
        if S[idx] == "L":
            if S[idx + 1] == "L":
                point += 1
        if S[idx] == "R":
            if S[idx - 1] == "R":
                point += 1

    point_list.append(point)

print(max(point_list))

Submission status: Wrong Answer

Solution code:
N, K = [int(_c) for _c in input().split(" ")]
S_orig = input()
point_list = []
for target, non_target in zip(["L", "R"], ["R", "L"]):
    S = list(S_orig)

    start_idx_list = []
    before_char = None
    for i, c in enumerate(S):
        if i == 0:
            start_idx_list.append(i)
            before_char = c
        else:
            if before_char == non_target and c == target:
                start_idx_list.append(i)
            before_char = c

    longest = 0
    start_idx = -1
    end_idx = -1
    for i in range(len(start_idx_list) - K):
        cur_length = start_idx_list[i + K] - start_idx_list[i] + 1
        if cur_length > longest:
            start_idx = start_idx_list[i]
            end_idx = start_idx_list[i + K]
            longest = cur_length

    for _idx in range(start_idx, end_idx):
        S[_idx] = target
    S = ["N"] + S + ["N"]

    point = 0
    for idx in range(1, N + 1):
        if S[idx] == "L":
            if S[idx + 1] == "L":
                point += 1
        if S[idx] == "R":
            if S[idx - 1] == "R":
                point += 1

    point_list.append(point)

print(max(point_list))

Submission status: Wrong Answer

Solution code:
N, K = [int(_c) for _c in input().split(" ")]
S = input()
point_list = []
for target, non_target in zip(["L", "R"], ["R", "L"]):
    S = list(S)

    start_idx_list = []
    before_char = None
    for i, c in enumerate(S):
        if i == 0:
            start_idx_list.append(i)
            before_char = c
        else:
            if before_char == non_target and c == target:
                start_idx_list.append(i)
            before_char = c

    longest = 0
    start_idx = -1
    end_idx = -1
    for i in range(len(start_idx_list) - K):
        cur_length = start_idx_list[i + K] - start_idx_list[i] + 1
        if cur_length > longest:
            start_idx = start_idx_list[i]
            end_idx = start_idx_list[i + K]
            longest = cur_length

    for _idx in range(start_idx, end_idx):
        S[_idx] = target
    S = ["N"] + S + ["N"]

    point = 0
    for idx in range(1, N + 1):
        if S[idx] == "L":
            if S[idx + 1] == "L":
                point += 1
        if S[idx] == "R":
            if S[idx - 1] == "R":
                point += 1

    point_list.append(point)

print(max(point_list))

Submission status: Wrong Answer

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

num_l = S.count("L")
num_r = S.count("R")

if num_l > num_r:
    target = "L"
    non_target = "R"
else:
    target = "R"
    non_target = "L"

S = list(S)

start_idx_list = []
before_char = None
for i, c in enumerate(S):
    if i == 0:
        start_idx_list.append(i)
        before_char = c
    else:
        if before_char == non_target and c == target:
            start_idx_list.append(i)
        before_char = c

longest = 0
start_idx = -1
end_idx = -1
for i in range(len(start_idx_list) - K):
    cur_length = start_idx_list[i + K] - start_idx_list[i] + 1
    if cur_length > longest:
        start_idx = start_idx_list[i]
        end_idx = start_idx_list[i + K]
        longest = cur_length

for _idx in range(start_idx, end_idx):
    S[_idx] = target
S = ["N"] + S + ["N"]

point = 0
for idx in range(1, N + 1):
    if S[idx] == "L":
        if S[idx + 1] == "L":
            point += 1
    if S[idx] == "R":
        if S[idx - 1] == "R":
            point += 1

print(point)