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:
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson, minimum_spanning_tree
from scipy.sparse import csr_matrix, coo_matrix, lil_matrix
import numpy as np
from collections import deque, Counter, defaultdict
from itertools import product, permutations,combinations
from operator import itemgetter
from heapq import heappop, heappush, heapify
from bisect import bisect_left, bisect_right, bisect
from fractions import gcd
from math import ceil,floor, sqrt, cos, sin, pi, factorial
from functools import reduce
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10**8)
INF = float('inf')
MOD = 10**9+7
def lcm_base(a, b):
    return (a * b) // gcd(a, b)

def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)


def main():
  N, M = map(int,readline().split())
  S = np.array(list(input()), dtype='U1')
  x = np.count_nonzero(S[1:] == S[:-1])
  
  x += 2*M
  x = min(x, N-1)
  print(x)
  
if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
N,K=map(int, sys.stdin.readline().split())
S=sys.stdin.readline().strip()
L=[]
cnt=0
for i,x in enumerate(S):
    if i==0:
        cnt+=1
        prev=x
    else:
        if prev==x: #前の文字と今の文字が同じ
            cnt+=1
        else:       #前の文字と今の文字が異なる
            L.append(cnt)
            cnt=1
        prev=x
else:
    L.append(cnt)

print sum(L)-max(1,len(L)-2*K)

Submission status: Accepted

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

cnt = 0
prev = ''

for i in range(len(s)):
    if s[i] == prev:
        cnt += 1
    else:
        prev = s[i]

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

Submission status: Accepted

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

# 初期の幸福度を計算
h = 0

for i in range(1, N):
    if S[i - 1] == S[i]:
        h += 1
        
# 基本的には１操作につき幸福度は2上がる

h += 2 * K

# 幸福度がN-1を超えることはない

if h > N - 1:
    h = N - 1
    
print(h)

Submission status: Accepted

Solution code:
import numpy as np
n,k = map(int,input().split())
s = input()
lr_cnt = 0
rl_cnt = 0
mnt = 0
for i in range(len(s)-1):
    if s[i] == 'L' and s[i+1] == 'R':
        lr_cnt += 1
        
    if s[i] == 'R' and s[i+1] == 'L':
        rl_cnt += 1
mnt  = rl_cnt + lr_cnt+1
mnt = np.max([1,mnt-2*k])
if mnt == 1:
    print(n-1)
else:
    print(n-rl_cnt-lr_cnt+2*k-1)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
X = S.count("RL")
Y = 0
if S[0] == "L":
    Y += 1
if S[-1] == "R":
    Y += 1

ans = 0
for a, b in zip(S, S[1:]):
    if a == b:
        ans += 1
ans += 2*min(K, X)
if K > X:
    ans += min(Y, K-X)
print(min(N-1, ans))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)
INF = 10**30

def main():
    n, k = list(map(int, input().strip().split()))
    s = input().strip()
    q = 0
    p = ''
    for c in s:
        if c != p:
            q += 1
        p = c
    # print(q)
    print(min(n-1, n - q + 2 * k))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    # 解説AC
    N, K = (int(i) for i in input().split())
    S = input()
    ans = 0  # 初期スコア
    for i in range(N-1):
        if S[i] == S[i+1]:
            ans += 1
    # 1回の操作で+2できる、最大スコアはN-1なのでminを取る
    print(min(ans + 2*K, N-1))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    # 解説AC
    N, K = (int(i) for i in input().split())
    S = input()
    from itertools import groupby
    g = len(list(groupby(S)))
    ans = N - g
    print(min(ans + 2*K, N-1))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

for i in range(N-1):
    if S[i] != S[i+1]:
        if c < K:
            if k == 0:
                k += 1
            else:
                ans += 2
                c += 1
                k = 0
    else:
        ans += 1

if k == 1 and c < K:
    ans += 1

print(ans)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


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

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

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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

def judge(str):
    cnt = 0
    t = None
    for i in range(len(str)):
        if str[i] == t:
            cnt+=1
            t = str[i]
        else: t = str[i]
    return cnt

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

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
print(min(n-1, ans + 2*k))

Submission status: Accepted

Solution code:
def main():
    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
    #from itertools import product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    #from operator import itemgetter

    #inf = 10**17
    #mod = 10**9 + 7

    n,k = map(int, input().split())
    s = input().rstrip()
    cnt = 0
    for i in range(n-1):
        if s[i]!=s[i+1]:
            cnt += 1
    a = cnt // 2
    b = cnt % 2
    if k<=a:
        print(n-2*(a-k)-1-b)
    else:
        print(n-1)



if __name__ == '__main__':
    main()

Submission status: Accepted

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

same = 0

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

diff = n-1-same

print(same + min(2*k,diff))

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
s = list(input())
ans = n-1
for i in range(1,n):
    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()
l=[]
ans=0
for i in range(1,n):
    if s[i]==s[i-1]:
        ans+=1
for i in s:
    if l!=[]:
        if l[-1]!=i:
            l.append(i)
    else:
        l.append(i)
#print(ans)
#print(l)
n=len(l)
for i in range(1,n,2):
    if i-1>=0 and i+1<n and k>0:
        ans+=2
 #       print('cat')
        k-=1
    elif i-1>=0 and i+1>=n and k>0:
  #      print('asdf')
        ans+=1
        k-=1
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
s = input()
count = 0 #境界の数
for i in range (0,n-1):
    if (s[i] != s[i+1]):
        count += 1
answer = min(len(s) - count - 1 + k*2, len(s) - 1)
print(answer)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# WA

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

START = S[0]
prev = S[0]
ans = 0
for i in range(1, N):
    s = S[i]

    # 一緒だったら+1
    if prev == s:
        ans += 1

    # 最後の時だけ場合わけ
    if i == N - 1:
        if s == START and K > 0:
            if prev != s:
                ans += 2
        else:
            if K > 0:
                ans += 1

    # 最後以外
    else:
        # 前と異なる
        if prev != s:
            if s == START and K > 0:
                ans += 2
                K -= 1

            prev = s


print(ans)

Submission status: Accepted

Solution code:
#python3
def main():
    n, k = map(int, input().split())
    s = input()
    sc = 0
    
    for i in range(n-1):
        if s[i] == s[i+1]:
            sc += 1
    ans = min(sc+2*k, n-1)
    print(ans)
main()

Submission status: Accepted

Solution code:
import sys

import bisect

# from collections import Counter, deque, defaultdict
# import copy
# from heapq import heappush, heappop, heapify
# from fractions import gcd

import itertools

# from operator import attrgetter, itemgetter
import math

# import numpy as np

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    n, k = list(map(int, readline().split()))
    stemp = input()
    s = "R"
    s += stemp
    s += "L"

    unhappy_edge = 0

    if s[1] == "L":
        unhappy_edge += 1
    if s[-2] == "R":
        unhappy_edge += 1

    unhappy_pair = 0
    prev = s[1]
    for i in range(2, n + 1):
        current = s[i]
        if prev == "R" and current == "L":
            unhappy_pair += 1
        prev = current

    temp = min(k, unhappy_pair)
    unhappy_pair -= temp
    k -= temp

    if k > 0:
        unhappy_edge = 1

    print(n - unhappy_pair * 2 - unhappy_edge)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:


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

    dlist = []
    dlist.append([s[0], 1])
    for c in s[1:]:
        if c == dlist[-1][0]:
            dlist[-1][1] += 1
        else:
            dlist.append([c, 1])

    curr = 0
    for i in range(1, len(dlist), 2):
        if curr < k:
            if dlist[i][0] == 'R':
                dlist[i][0] = 'L'
            else:
                dlist[i][0] = 'R'
            curr += 1

    unhappy = 0
    for i in range(len(dlist) - 1):
        if dlist[i][0] == 'R' and dlist[i + 1][0] == 'L':
            unhappy += 2
    if dlist[0][0] == 'L':
        unhappy += 1
    
    if dlist[-1][0] == 'R':
        unhappy += 1

    print(n - unhappy)

submit()

Submission status: Accepted

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

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

p = (w // 2) * [2] + (w % 2) * [1]

print(ans + sum(p[:k]))

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
input_nums = lambda: list(map(int, input().split()))

def main():
    N, K = input_nums()
    S = input()
    now=''
    cnt=0
    for s in S:
        if s!=now:
            cnt+=1
        now=s
    """
    cnt => 不幸な人の数+1(最初のみ無条件でインクリメントしているため)
    N-1 => 最大の幸福数（端の人は前に人がいないため-1）
    N-cnt =>
        初期状態の幸福な人の数．
        正確には (N-1) - (cnt-1)である．
        これは最初のcntのインクリメントが無条件に行われるため．
    2*K =>
        1回の操作で幸福な人を2人増やせるので
        K回の操作では2*K人を幸福にできる
    """
    ans = min(N-1, N-cnt+2*K)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
N,K=map(int,input().split())

S=list(input())

clu=[]
temp=0
for i in range(1,len(S)):
    if S[i]==S[i-1]:
        temp+=1
    else:
        clu.append(temp)
        temp=0
clu.append(temp)
 
ans=sum(clu)

base=S[0]

zone=False
for i in range(1,len(S)):
    if zone:
        if S[i]==base:
            K-=1
            ans+=2
            zone=False
        else:
            S[i]=base
    else:
        if S[i]!=base and K>0:
            zone=True
            S[i]=base

if zone:
    ans+=1

print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
S=input()
now="0"
cnt=0
for s in S:
    if s!=now:
        cnt+=1
    now=s

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

Submission status: Accepted

Solution code:
import sys
import numpy as np

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

N, K = lr()
S = np.array(list(sr()))
answer = (S[:-1] == S[1:]).sum()
answer += 2 * K
answer = min(answer, N-1)
print(answer)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

def ri():
    return int(input())

def rl():
    return list(input().split())

def rli():
    return list(map(int, input().split()))

def calc(s, k):
    ret = 0
    rev = 0
    c = s[0]
    for i in range(1, len(s)):
        if s[i] == c:
            ret += 1
            continue
        rev += 1
        c = s[i]
    ret += min(rev, k*2)
    k -= rev//2
    return ret


def main():
    n, k = rli()
    s = input()
    rs = ""
    for i in range(len(s)):
        if (s[n-i-1] == 'L'): rs += 'R'
        else: rs += 'L'
    a1 = calc(s,k)
    a2 = calc(rs,k)
    # print(s)
    # print(rs)
    print(max(a1, a2))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

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

print(ans)

Submission status: Accepted

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

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

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

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

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

print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
S = str(input())
hap = 0
for i in range(1, len(S)):
    if S[i-1] == S[i]:
      hap += 1
ans = min(hap + k*2, n-1)
print(ans)

Submission status: Accepted

Solution code:
# 解説見た後に作ったやつ
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

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

    rev = False
    ans = 0
    rev_count = 0
    for i in range(1,N):
        if S[i] == S[i-1]:
            ans += 1
            rev = False
        else:
            if not rev and rev_count < K:
                rev_count += 1
                rev = True

            if rev:
                S[i] = 'L' if S[i] == 'R' else 'R'
                ans += 1


    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

    rev = False
    rev_count = 0
    for i in range(1,N):
        if S[i] == S[i-1]:
            rev = False
        else:
            if not rev and rev_count < K:
                rev_count += 1
                rev = True

            if rev:
                S[i] = 'L' if S[i] == 'R' else 'R'


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

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math
import time
from collections import deque
from collections import defaultdict
from copy import deepcopy
import heapq

mod = 10 ** 9 + 7
t = time.time()



def iip():
    ret = [int(i) for i in input().split()]
    if len(ret) == 1:
        return ret[0]
    return ret


def main():
    N, K = iip()
    S = input()
    happy = 0
    for i in range(N):
        if i != 0 and S[i] == "L" and S[i-1] == "L":
            happy += 1
            continue
        if i != N-1 and S[i] == "R" and S[i+1] == "R":
            happy += 1
            continue
    happy += 2*K
    happy = min(happy, N-1)

    print(happy)



main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
n,k = list(map(int,input().split()))
s = input()
rl_cnt = s.count("RL")
ret = 0
s0 = s[0]
sn = s[-1]
if s0==sn:
    ret=n-1-2*max(0,rl_cnt-k)
elif s0=="L" and sn=="R":
    if k<=rl_cnt:
        ret=n-2-2*(rl_cnt-k)
    else:
        ret=n-1
else:
    if k<rl_cnt:
        ret = n - 2*(rl_cnt-k)
    else:
        ret = n-1
print(ret)

Submission status: Accepted

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

s=input()
ANS=[]
cnt=0
if s[0]=='L':
    for i in range(n-1):
        if s[i]=='R' and s[i+1]=='L':
            cnt+=1
    if s[n-1]=='R':
        cnt+=1
    if cnt<=k:
        ANS.append(n-1)
    else:
        if s[n-1]=='R':
            ANS.append(n-1-1-2*(cnt-k-1))
        else:
            ANS.append(n-1-2*(cnt-k))
CNT=0
if s[0]=='R':
    for i in range(n-1):
        if s[i]=='L' and s[i+1]=='R':
            CNT+=1
    if s[n-1]=='L':
        CNT+=1
    if CNT<=k:
        ANS.append(n-1)
    else:
        if s[n-1]=='L':
            ANS.append(n-1-1-2*(CNT-k-1))
        else:
            ANS.append(n-1-2*(CNT-k))

print(max(ANS))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
ans,p=0,0
for i in range(n-1):
    if s[i]==s[i+1]: ans+=1
    else: p+=1

ans+=min(p,2*k)
print(ans)

Submission status: Accepted

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

pre=s[0]
tmp=0
ans=0
check=0
for i in range(1, n):
    if s[i] != pre:
        check+=1
        pre=s[i]
        if check%2==1 and tmp < k:
            tmp+=1
            ans+=1
        if check%2==0 and tmp < k+1:
            ans+=1
            if tmp == k:
                tmp+=1
    else:
        ans+=1

print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
D - Face Produces Unhappiness
https://atcoder.jp/contests/abc140/tasks/abc140_d

"""
import sys

import re

def solve(N, K, S):
    x = len(re.findall(r'RL', S))
    y = (S[0] == 'L') + (S[-1] == 'R')
    ans = N - 2 * x - y
    exe = min(x, K)
    K -= exe
    ans += 2 * exe
    while K and y:
        ans += 1
        K -= 1
        y -= 1
    return min(ans, N-1)


def main(args):
    N, K = map(int, input().split())
    S = input()
    ans = solve(N, K, S)
    print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Accepted

Solution code:
def solve():
    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

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


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
#140_D
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(n-1, score + k * 2))

Submission status: Accepted

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

def main():
    n,k=map(int,input().split())
    s=input()
    g=1
    for a,b in zip(s,s[1:]):
        if a!=b:
            g+=1
    print(n-max(1,g-2*k))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

N, M = map(int, input().rstrip().split())
A = input()

count = 0
for i in range(N-1):
    if A[i] == A[i+1]:
        count += 1
        
print(min(count + 2 * M, N - 1))

Submission status: Accepted

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

A = 0
B = 0

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

if S[0] == "R" and S[N-1] == "L":
    A -= 1
    B += 1
elif S[0] == "L" and S[N-1] == "R":
    B += 1

ans = A * 2 + B + 1

while(K > 0):
    if A > 0:
        ans -= 2
        A -= 1
    elif B > 0:
        ans -= 1
        B -= 1
    else:
        break
    K -= 1

print(N - ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
S = input()
unhappy = 1
for i in range(N-1):
    if(S[i]!=S[i+1]):
        unhappy += 1
change = 2*K
fin_unhappy= max(1,unhappy-change)
print(N-fin_unhappy)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import sys
import numpy as np
import heapq


def input():
    return sys.stdin.readline()[:-1]


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


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
s = input()
ans = s.count("RL") * 2
ans1 = 0
if s[0]=="L":
	ans1 += 1
if s[-1]=="R":
	ans1 += 1
while k > 0:
	if ans > 0:
		if ans == 2 and ans1 == 0:ans1 += 1;ans -= 2;break
		ans -= 2
	elif ans1 == 2:
		ans1 -= 1
	k -= 1
print(n - ans - ans1)

Submission status: Accepted

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

cnt = 0

if S[0] == "L":
    cnt += 1

ans = 0

for i in range(N - 1):
    if S[i:i + 2] == "RL":
        cnt += 1
    if S[i] == S[i + 1]:
        ans += 1

if cnt - K >= 1:
    ans += K * 2
else:
    ans = N - 1

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = list(input())
count = 0
f = True
for i in range(N - 1):
    if S[i] == S[i + 1]:
        count += 1
ans = count + 2 * K
if ans < N - 1:
    print(ans)
else:
    print(N - 1)

Submission status: Accepted

Solution code:
import math 
import bisect
import heapq
from collections import deque

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

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

same = n-1-dif
if k > dif // 2:
    ans = n-1
else: ans = same + 2*k

print(ans)

Submission status: Accepted

Solution code:
def main():
    length, operation = map(int, input().split())
    direction = list(input())
    before = ""
    inverse = {"L": "R", "R": "L"}
    change = 0
    section = 0
    answer = 0
    for i in range(length):
        if not before == direction[i]:
            before = direction[i]
            section += 1
            if section % 2:
                change += 1
        if section % 2 == 0 and change <= operation:
            direction[i] = inverse[direction[i]]
    for i in range(1, length):
        if direction[i] == direction[i - 1]:
            answer += 1
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

nowLR = S[0]
group_num = 1
for i in range(1, N):
    if S[i] != nowLR:
        group_num += 1
        nowLR = S[i]

max_rev = int(group_num / 2)
if max_rev <= K:
    print(N-1)
else:
    print(N - (group_num - 2 * K))

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import heapq
import sys
def input():
    return sys.stdin.readline()[:-1]

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

if __name__ == "__main__":
    main()

Submission status: Accepted

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

s += 'x'
l = list()
cnt = 1
for i in range(1,n+1):
  if s[i]!=s[i-1]:
    l.append(cnt)
    cnt = 1
  else:
    cnt += 1

m = min(2*k+1, len(l))
ans = sum(l[0:m]) - 1 

for j in range(m,len(l)):
  ans += l[j] - 1

print(ans)

Submission status: Accepted

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

see = s[0]
cnt = 0
cluster = 1
for i in range(1, n):
    if see == s[i]:
        cnt += 1
    else:
        see = s[i]
        cluster += 1

for i in range(k):
    if cluster > 2:
        cluster -= 1
        cnt += 2
    else:
        print(n - 1)
        exit()
print(min(cnt, n - 1))

Submission status: Accepted

Solution code:
# Author: cr4zjh0bp
# Created: Thu Mar  5 16:04:44 UTC 2020
import sys
 
stdin = sys.stdin
inf = 1 << 60
mod = 1000000007
 
ni = lambda: int(ns())
nin = lambda y: [ni() for _ in range(y)]
na = lambda: list(map(int, stdin.readline().split()))
nan = lambda y: [na() for _ in range(y)]
nf = lambda: float(ns())
nfn = lambda y: [nf() for _ in range(y)]
nfa = lambda: list(map(float, stdin.readline().split()))
nfan = lambda y: [nfa() for _ in range(y)]
ns = lambda: stdin.readline().rstrip()
nsn = lambda y: [ns() for _ in range(y)]
ncl = lambda y: [list(ns()) for _ in range(y)]
nas = lambda: stdin.readline().split()

n,k=na()
s=ns()

p,q=[0]*2
for i in range(n-1):
    if s[i]==s[i+1]:
        p+=1
    else:
        q+=1

if 2*k>=q:
    print(p+q)
else:
    print(p+2*k)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
a = 0
i = 1
while i < N:
	if S[i - 1] == S[i]:
		a += 1
	i += 1
print(min(N - 1, K * 2 + a))

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, K = MAP()
S = input()

point = 0

# default
for i in range(N-1):
    if S[i] == S[i+1]:
        point += 1


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

Submission status: Accepted

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

# Summarize count of factor within list -- START --
def summarize_list(sl):

  a=sl[0]
  c=1
  res=[]

  for x in sl[1:]:
    if x==a:
      c+=1
    else:
      res.append(c)
      a=x
      c=1
  res.append(c)

  return res
# Summarize count of factor within list --- END ---

def main():
  n,k=LI()
  s=list(S())

  s=summarize_list(s)

  if 2*k+1>=len(s):
    return n-1

  s=[0]+s

  for i in range(len(s)-1):
    s[i+1]+=s[i]
  # print(s)

  l1=[0]*len(s)
  l2=[0]*len(s)

  for i in range(1,len(s)):
    l1[i]+=l1[i-1]
    l1[i]+=s[i]-s[i-1]-1

  for i in range(1,len(s))[::-1]: 
    l2[i-1]+=l2[i]
    l2[i-1]+=s[i]-s[i-1]-1

  # print(s)
  # print(l1)
  # print(l2)

  ans=-inf
  for i in range(len(s)-(2*k+1)):
    a=s[2*k+1+i]
    b=s[i]
    # print(a,b)
    c=l1[i]
    d=l2[2*k+1+i]
    ans=max(ans,a-b+c+d)

  return ans-1

# main()
print(main())

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
s = 'R' + input() + 'L'

score = 0
for i in range(1,n+1):
  if s[i] == 'R' and s[i+1] =='R':
    score += 1
  elif s[i] =='L' and s[i-1]=='L':
    score += 1
print(min(n-1,score+2*k))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
ans=0
for i,j in zip(s,s[1:]):
      if i==j:
            ans+=1

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

Submission status: Accepted

Solution code:
import math


class Solution:

    def solve(self, N: int, K: int, S):

        num_change = 0
        hapiness = 0

        prev = ""

        for s in S:
            if prev == s:
                hapiness += 1
            elif prev != "":
                num_change += 1

            prev = s

        return hapiness + min(num_change, 2 * K)


if __name__ == '__main__':

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

    # solve
    solution = Solution()
    print(solution.solve(N, K, S))

Submission status: Accepted

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

Submission status: Accepted

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
print(min(cnt + 2 * K, N - 1))

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
S = input()+"W"
A = []
a = 0
b = ""
for s in S:
    if b!="" and b!=s:
        A.append(a)
        a=1
    else:a+=1
    b = s
ans = 0
for a in A:ans+=(a-1)
print(min(N-1,ans+2*K))