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:
n, k = map(int, input().split())
s = input()

unhappiness = 0
m1, m2 = 0, 0

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

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

Submission status: Wrong Answer

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

i = 0
m = 0
for i in range(n-1):
    if s[i] == 'R' and s[i+1] == 'L':
        m += 1
if m >= k:
    m -= k
    k = 0
else:
    m = 0
    k -= m
m *= 2
if s[0] == 'L':
    m += 1
if s[-1] == 'R':
    m += 1

m = max(m-k, 0)
print(n-m)

Submission status: Wrong Answer

Solution code:

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

    n, k = map(int, input().split())
    s = input()
    n = len(s)
    ans = 0
    for i in range(n-1):
        if s[i+1] == s[i]:
            ans += 1
    x = s.count('RL')
    y = 0
    if s[0]=='L' and s[-1] == 'R':
        y =1
    if x > 0:
        ans += 2* min(x-1, k)
        k -= x-1
        if k > 0:
            ans += 1
            k -=1
    if  k > 0:
        ans += y
    print(ans)
    

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:

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

    n, k = map(int, input().split())
    s = input()
    n = len(s)
    ans = 0
    for i in range(n-1):
        if s[i+1] == s[i]:
            ans += 1
    x = s.count('RL')
    y = 0
    if s[0]=='L':
        y+= 1
    if s[-1]=='R':
        y+=1
    if x-1 < k:
        ans += 2*max(0, x-1)
        k-=max(x-1,0)
        ans += min(k, y+1)
    else:
        ans += 2*k
    print(ans)
    

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:

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

    n, k = map(int, input().split())
    s = input()
    n = len(s)
    st, ed = 0, n-1
    i = 0
    cnt = 1
    for i in range(n-1):
        if s[i+1] != s[i]:
            cnt += 1

    for i in range(k):
        l, r = s[st], s[ed]
        if s == 'L'*n or s == 'R'*n:
            print(n-1)
            return
        while st < ed and s[ed]==r:
            ed -= 1
        while st < ed and s[st] == l:
            st += 1
        tmp = s[st:ed+1].replace('L', 'X').replace('R', 'L').replace('X', 'R')
        tmp = tmp[::-1]
        s = s[:st]+tmp+s[ed+1:]
        cnt -= 2
    ans = n-cnt
    print(ans)

    
        
             


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from itertools import groupby
n, k = map(int, input().split())
list_S = list(input())

group = groupby(list_S)
list_G = []
ans = 0

for key, g in group:
    j = len(list(g))
    list_G.append([key, j])
    ans += j - 1

h = len(list_G)
l, r = [], []

for i in range(h):
    if list_G[i][0] == "L":
        if i == 0 or i == h-1:
            l.append(1)
        else:
            l.append(2)
    elif list_G[i][0] == "R":
        if i == 0 or i == h-1:
            r.append(1)
        else:
            r.append(2)

l.sort(reverse=True)
r.sort(reverse=True)
p, q = ans, ans

if len(l) <= k:
    p += sum(l)
else:
    p += sum(l[:k])

if len(r) <= k:
    q += sum(r)
else:
    q += sum(r[:k])

print(max(p, q))

Submission status: Wrong Answer

Solution code:
from itertools import groupby
n, k = map(int, input().split())
list_S = list(input())

group = groupby(list_S)
list_G = []
ans = 0

for key, g in group:
    j = len(list(g))
    list_G.append([key, j])
    ans += j - 1

h = len(list_G)
l, r = [], []

for i in range(h):
    if list_G[i][0] == "L":
        if i == 0 or i == h-1:
            l.append(1)
        else:
            l.append(2)
    elif list_G[i][0] == "R":
        if i == 0 or i == h-1:
            r.append(1)
        else:
            r.append(2)

l.sort(reverse=True)
r.sort(reverse=True)
p, q = ans, ans

if len(l) < k:
    p += sum(l)
else:
    p += sum(l[:k])

if len(r) < k:
    q += sum(r)
else:
    q += sum(r[:k])

print(max(p, q))

Submission status: Wrong Answer

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

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

print(ans)

Submission status: Wrong Answer

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

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

print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:

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

Submission status: Wrong Answer

Solution code:
import heapq
t = 1
def max(a,b):
	if a > b:
		return a
	return b
while t > 0:
	t -= 1
	n,k = map(int,input().split())
	# n = int(input())
	# a = list(map(int,input().strip().split()))[0:n]
	# b = list(map(int,input().strip().split()))[0:n]
	# c = list(map(int,input().strip().split()))[0:n-1]
	s = input()
	i = 0
	ans = 0
	c = 0
	while(i < n):
		j = i
		c += 1
		while j+1 < n and s[j+1] == s[i]:
			j += 1
		l = j-i+1
		ans += (l-1)
		i = j+1
	if k < c-1:
		ans += 2*k
	else:
		ans += 2*(c-2)
		ans += 1
	# ans += min(2*(c-1),2*k)
	print(ans)
	# print(m)

Submission status: Wrong Answer

Solution code:
import heapq
t = 1
def max(a,b):
	if a > b:
		return a
	return b
while t > 0:
	t -= 1
	n,k = map(int,input().split())
	# n = int(input())
	# a = list(map(int,input().strip().split()))[0:n]
	# b = list(map(int,input().strip().split()))[0:n]
	# c = list(map(int,input().strip().split()))[0:n-1]
	s = input()
	i = 0
	ans = 0
	c = 0
	while(i < n):
		j = i
		c += 1
		while j+1 < n and s[j+1] == s[i]:
			j += 1
		l = j-i+1
		ans += (l-1)
		i = j+1
	# print(ans)
	ans += min(2*(c-1),2*k)
	# if(k < c-1):
	# 	ans += 2*k
	# else:
	# 	ans += 2*(c-2)
	# 	ans += 1
	# ans += min(c*2,k*2)
	print(ans)
	# for i in range(1,n-1):

		# if k == 0:
		# 	break
		# if(s[i] == 'L' and s[i+1] == 'R' and s[i-1] == 'R'):
		# 	s[i] = 'R'
		# elif s[i] == 'R' and s[i+1] == 'L' and s[i-1] == 'L':
		# 	s[i] = 'L'

	# print(n*n*n)
	# m = 1000
	# i = 0
	# while i < n:
	# 	j = i
	# 	while j+1 < n and v[j+1] >= v[j]:
	# 		j += 1
	# 	x = m//v[i]
	# 	m = m%v[i]
	# 	temp = x*v[j]
	# 	m += temp
	# 	i = j+1
	# print(m)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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

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

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

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

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

Submission status: Wrong Answer

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

A = []
pre = S[0]
cnt = 1
for i in range(1,N):
  if pre == S[i]:
    cnt += 1
  else:
    pre = S[i]
    A.append(cnt)
    cnt = 1
A.append(cnt)

ans = sum(A) - len(A)
# X は真ん中。Yは端っこ。引数はIndexのMOD2。
X,Y = [0,0], [0,0]
for i in range(len(A)):
  if i == 0 or i == len(A)-1:
    Y[i%2] += 1
  else:
    X[i%2] += 1
    
wk = [0,0]
for i in range(2):
  if K <=X[i]:
    wk[i] = K * 2
  elif K <= X[i] + Y[i]:
    wk[i] = X[i] * 2 + (K-X[i])
  else:
    wk[i] = X[i] * 2 + Y[i]

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

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
import sys
import re
from collections import deque, defaultdict
from itertools import combinations, combinations_with_replacement
import bisect
from math import factorial, sqrt, log, ceil, floor
sys.setrecursionlimit(1000000)


def main():
    input = sys.stdin.readline
    #N, M = map(int, input().split())
    #N, K = map(int, input().split())
    #ps = list(map(int, input().split()))

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

    S += 'D'  # dummy

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

        if prev[0] == s:
            continue

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

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

    print(happy)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
import sys
import re
from collections import deque, defaultdict
from itertools import combinations, combinations_with_replacement
import bisect
from math import factorial, sqrt, log, ceil, floor
sys.setrecursionlimit(1000000)


def main():
    input = sys.stdin.readline
    #N, M = map(int, input().split())
    #N, K = map(int, input().split())
    #ps = list(map(int, input().split()))

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

    S += 'D'  # dummy

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

        if prev[0] == s:
            continue

        happy += (i - 1) - prev[1]
        if prev[0] == 'R':
            if prev[1] == 0 or i - 1 == N - 1:
                one += 1
            else:
                two += 1
        prev = (s, i)

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

    print(happy)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
s = input()
score = -1
g = ""
prev_c = s[0]
for i in range(len(s)):
    c = s[i]
    if i == len(s) - 1:
        if c == prev_c:
            score += 1
            g += prev_c
        else:
            g += prev_c
            g += c
    elif c == prev_c:
        score += 1
    else:
        g += prev_c
        prev_c = c

if (len(g) - 2) > 0:
    score += min((len(g) - 2), k) * 2
    k = min(0, k - len(g) - 2)

if k > 0 and len(g) > 0 and g[0] != g[-1]:
    score += 1

print(score)

Submission status: Wrong Answer

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

N,K=(int(x) for x in input().rstrip('\n').split())
L = list(input())
now = L[0]
change = 0
for x in L:
  if x != now:
    change += 1
    now = x
ok = 0
for i in range(K):
  if change == 0:
    ok += 1
    print(N-1)
    break
  elif change==1:
    change -= 1
  else:
    change -= 2
if ok == 0:
  print(N-1-change)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
import sys
from io import StringIO
import unittest
import os

# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)


# 実装を行う関数
def resolve(test_def_name=""):
    # 数値取得サンプル
    n, k = map(int, input().split())
    s_s = list(input())

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

    # 処理を実施
    target = ""
    point = 0
    actcnt = 0
    for cnt, s in enumerate(s_s):

        if actcnt == k:
            break

        if target == "":
            target = s
            continue

        if (target == s and point != 0) or (target != s and cnt == len(s_s) - 1):

            if target != s and cnt == len(s_s) - 1:
                cnt += 1

            for works in range(point, cnt):
                if s_s[works] == "R":
                    s_s[works] = "L"
                else:
                    s_s[works] = "R"
            target = s
            point = 0
            actcnt += 1
            continue

        if target != s and point == 0:
            point = cnt
            continue

    # 処理後、要素を数え上げる。
    ans = 0
    for cnt, s in enumerate(s_s[1:], start=1):
        bef_str = s_s[cnt - 1]
        if bef_str == s:
            ans += 1

    print(ans)


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

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

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

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

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

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

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

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def tes_t_1original_1(self):
        test_input = """データ"""
        output = """データ"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Wrong Answer

Solution code:
import sys
from io import StringIO
import unittest
import os

# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)


# 実装を行う関数
def resolve(test_def_name=""):
    # 数値取得サンプル
    n, k = map(int, input().split())
    s_s = list(input())

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

    # 処理を実施
    target = ""
    point = 0
    actcnt = 0
    for cnt, s in enumerate(s_s):

        if actcnt == k:
            break

        if target == "":
            target = s
            point = 0

        if (target == s and point != 0) or (target != s and cnt == len(s_s) - 1):

            if target != s and cnt == len(s_s) - 1:
                cnt += 1

            for works in range(point, cnt):
                if s_s[works] == "R":
                    s_s[works] = "L"
                else:
                    s_s[works] = "R"
            target = ""
            point = 0
            actcnt += 1
            continue

        if target != s and point == 0:
            point = cnt
            continue

    # 処理後、要素を数え上げる。
    ans = 0
    for cnt, s in enumerate(s_s[1:], start=1):
        bef_str = s_s[cnt - 1]
        if bef_str == s:
            ans += 1

    print(ans)


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

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

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

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

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

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def tes_t_1original_1(self):
        test_input = """データ"""
        output = """データ"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Wrong Answer

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

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

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

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

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

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

Submission status: Wrong Answer

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

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

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

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

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

print(max(happy+sum(lchunk[:k]), happy+sum(rchunk[:k])))

Submission status: Wrong Answer

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

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

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

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

print(max(happy+sum(lchunk[:k]), happy+sum(rchunk[:k])))

Submission status: Wrong Answer

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

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

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

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

print(happy)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
s=input()
r=[]
l=[]
ans = 0
for i, j in zip(s[:-1], s[1:]):
  if i == j:
    ans += 1
  
for i in s.split("L"):
  if i:
    r.append(i)
for i in s.split("R"):
  if i:
    l.append(i)
m = min(len(l),len(r))
temp = min(m,k)*2
if m <= k:
  temp -= 1
print(ans + temp)

Submission status: Wrong Answer

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

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

if ans==n :
   print(ans-1)
   quit()

print(ans)

Submission status: Wrong Answer

Solution code:
n,k=list(map(int,input().split()))
S=input()
c,row_count=S[0],1

for s in S:
  if c != s:
    c = s
    row_count += 1

if row_count-1 <= k:
  row_count = 1
else:
  row_count -= k*2
  
print(n-row_count)

Submission status: Wrong Answer

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

rl_cnt = 0
for s1,s2 in zip(s[:-1],s[1:]):
    if s1 == 'R' and s2 == 'L':
        rl_cnt += 1

left_happy = 1 if s[0] == 'R' else 0
right_happy = 1 if s[-1] == 'L' else 0

first_happy = n - rl_cnt*2 -2 + left_happy + right_happy
# print(first_happy)
if k <= rl_cnt:
    print(first_happy + k*2)
else:
    rem = k-rl_cnt
    ans = first_happy + rl_cnt*2 + min(rem, 2-left_happy+right_happy)
    print(ans)

Submission status: Wrong Answer

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

rl_cnt = 0
for s1,s2 in zip(s[:-1],s[1:]):
    if s1 == 'R' and s2 == 'L':
        rl_cnt += 1

left_happy = 1 if s[0] == 'R' else 0
right_happy = 1 if s[-1] == 'L' else 0

first_happy = n - rl_cnt*2 -2 + left_happy + right_happy
# print(first_happy)
if k <= rl_cnt:
    print(first_happy + k*2)
else:
    rem = k-rl_cnt
    ans = first_happy + rl_cnt*2 + min(rem, left_happy+right_happy)
    print(ans)

Submission status: Wrong Answer

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

rl_cnt = 0
for s1,s2 in zip(s[:-1],s[1:]):
    if s1 == 'R' and s2 == 'L':
        rl_cnt += 1

left_happy = 1 if s[0] == 'R' else 0
right_happy = 1 if s[-1] == 'L' else 0

first_happy = n - rl_cnt*2 -2 + left_happy + right_happy
print(first_happy)
if k <= rl_cnt:
    print(first_happy + k*2)
else:
    rem = k-rl_cnt
    ans = first_happy + rl_cnt*2 + min(rem, left_happy+right_happy)
    print(ans)

Submission status: Wrong Answer

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

rl_cnt = 0
for s1,s2 in zip(s[:-1],s[1:]):
    if s1 == 'R' and s2 == 'L':
        rl_cnt += 1

left_happy = 1 if s[0] == 'R' else 0
right_happy = 1 if s[-1] == 'L' else 0

first_happy = n - rl_cnt*2 -2 + left_happy + right_happy

if k <= rl_cnt:
    print(first_happy + k*2)
else:
    rem = k-rl_cnt
    ans = first_happy + k*2 + min(rem, left_happy+right_happy)
    print(ans)

Submission status: Wrong Answer

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

x = sum(S[i] == "R" and S[i + 1] == "L" for i in range(N - 1))
y = int(S[0] == "L") + int(S[-1] == "R")
res = N - 2 * x - y

ans = res + 2 * min(K, x)
if K - x > 0 and y > 0:
    ans += 1
print(ans)

Submission status: Wrong Answer

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

x = sum(S[i] == "R" and S[i + 1] == "L" for i in range(N - 1))
y = int(S[0] == "L") + int(S[-1] == "R")
res = N - 2 * x - y

ans = res + 2 * min(K, x) + max(0, min(1, K - x))
print(ans)

Submission status: Wrong Answer

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

x = sum(S[i] == "R" and S[i + 1] == "L" for i in range(N - 1))
y = int(S[0] == "L") + int(S[-1] == "R")
res = N - 2 * x - y

ans = res + 2 * min(K, x) + max(0, min(y, K - x))
print(ans)

Submission status: Wrong Answer

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

def run_length_encoding(text:str)->list:
    text += '_'
    c = text[0]
    x = 1
    res = []
    for i in range(1, len(text)):
        if c == text[i]:
            x += 1
        else:
            res.append((c, x))
            c = text[i]
            x = 1
    return res

rle = run_length_encoding(S)
gr = len(rle)
hp = 0
for c, x in rle:
    hp += x - 1

if gr == 1:
    ans = hp
elif gr == 2:
    ans = hp + 1
else:
    ans = hp + min(K, gr//2) * 2
print(ans)