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:
N,K = [int(x) for x in  input().split()]
S = list(input())
ans = [0]
a = []
for i in range(N-1):
  if S[i]!=S[i+1]:
  	ans.append(i)
ans.append(N-1)
#print(ans)
a = []
for i in range(1,len(ans)):
  a.append(ans[i]-ans[i-1])
a[0] +=1
ans2 = sum(a)-len(a)
#print(a)
#print(ans2)
#print(len(a)//2*2-1)
if len(a)!=1:
  ans2 = ans2 +(2*K)
print(min(ans2,len(S)-1))

Submission status: Accepted

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

largest = 0
largest_left_index = -1

sum_list = list()

count = 0
for i in range(N):
    if S[i] == "L":
        if count <= 0:
            count = count - 1
        else:
            sum_list.append(count)
            count = -1
    elif S[i] == "R":
        if count >= 0:
            count = count + 1
        else:
            sum_list.append(-count)
            count = 1
else:
    sum_list.append(count) if count > 0 else sum_list.append(-count)

happines = 0
for i in range(len(sum_list)):
    happines = happines + sum_list[i] - 1

length = len(sum_list)

for i in range(K):
    if length > 2:
        happines = happines + 2
        length = length - 2
    elif length == 2:
        happines = happines + 1
        length = length - 1

print(happines)

Submission status: Accepted

Solution code:
def solve_d(n, k, s):
    res = 0
    for i in range(n - 1):
        if s[i] == s[i + 1]:
            res += 1
    d = n - 1 - res
    if 2 * k > d:
        return n - 1
    else:
        return res + 2 * k


def main():
    n, k = map(int, input().split())
    s = list(input())
    print(solve_d(n, k, s))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from copy import deepcopy
import itertools
from bisect import bisect_left
from bisect import bisect_right
import math
from collections import deque
from collections import Counter


def read():
    return int(input())


def readmap():
    return map(int, input().split())


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


INT_MAX = 10 ** 10


if __name__ == "__main__":
    N, K = readmap()
    S = input()

    happynum = sum([S[i] == S[i-1] for i in range(1, N)])
    print(min(happynum + 2 * K, N - 1))

Submission status: Accepted

Solution code:
import math
import queue

mod = 1e9+7

def swap(a,b):
    return (b,a)

def gcd(a,b):
    if (a<b):
        a,b = swap(a,b)
    if (b==0):
        return a
    else:
        return gcd(b,a%b)

def divisors(a):
    divisors = []
    for i in range(1,int(a**0.5)+1):
        if a%i==0:
            divisors.append(i)
            if i!=a//i:
                divisors.append(a//i)
    return divisors

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

if __name__ == '__main__':
    main()

Submission status: Accepted

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

l = []

i = 0
last = "H"
cnt = 0
for i in range(len(s)-1):
    if (s[i] == s[i+1]):
        cnt+=1


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

Submission status: Accepted

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

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
import numpy as np
s_int = np.array([0]*n)
for i in range(n):
  if s[i] == 'L':
    s_int[i] = -1
  else:
    s_int[i] = 1
    

for l in range(1, n-1):
  if k == 0:
    break
  if s_int[l] != s_int[l-1]:
    for r in range(l+1, n):
      if s_int[r] == s_int[l-1]:
        part = s_int[l:r]
        s_int[l:r] = part[::-1] * -1
        k -= 1
        break

if k > 0:
  print(n-1)
  exit()
ans = n-1
for i in range(1, n):
  if s_int[i] != s_int[i-1]:
    ans -= 1
print(ans)

Submission status: Accepted

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

block_count = 0
ans = 0
last = 0
for i in range(N):
	if S[i] != last:
		last = S[i]
		block_count += 1
	if S[i] == "L" and  i > 0 and S[i-1] == "L": ans += 1
	if S[i] == "R" and  i < N-1 and S[i+1] == "R": ans += 1

half = (block_count - 1)//2

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

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

for i in range(1,n+2):
    if s[i-1]=='R' and s[i]=='L':
        if i==1 or i==n+1:
            count1+=1
        else:
            count2+=1
            
ans=n-(count1+count2*2)

if k<=count2:
    print(ans+k*2)
else:
    print(n-1)

Submission status: Accepted

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

ans = 0

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

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

Submission status: Accepted

Solution code:
# -*- 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



N, K = list(map(int, input().split()))
S = input()
    
def main():
    res = N
    past = S[0]
    cnt = K
    cnt2= 0
    if N == 1:
        return print(0)
    flg = False
    for n in range(1, N):
        now = S[n]
        #print(past, now, res)
        if past == "R" and now == "L":
            #print(n, ": BAD")
            res -= 2
            flg = True
        if past == "L" and now == "R" and flg == True:
            if 0 < cnt:
                #print("reverse")
                res += 2
                cnt -= 1
                cnt2 += 1
            flg = False
        past = now
    
    if flg == True and 0 < cnt:
        res += 1
    #print("Reach edge: ", res)
    if S[0] == "L":
        #print(0, ": edge BAD")
        res -= 1
        if 0 < cnt and ("R" in S) :
            #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: Accepted

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
    cnt2= 0
    if N == 1:
        return print(0)
# =============================================================================
#     if N == 2:
#         if (S[0] == "R" and S[1] == "L") or (S[0] == "L" and S[1] == "R"):
#             if 0 < cnt:
#                 return print(1)
#             else:
#                 return print(0)
#         
#         if (S[0] == "R" and S[1] == "R") or (S[0] == "L" and S[1] == "L"):
#             return print(1)
#     
# =============================================================================
    flg = False
    for n in range(1, N):
        now = S[n]
        #print(past, now, res)
        if past == "R" and now == "L":
            #print(n, ": BAD")
            res -= 2
            flg = True
        if past == "L" and now == "R" and flg == True:
            if 0 < cnt:
                #print("reverse")
                res += 2
                cnt -= 1
                cnt2 += 1
            flg = False
        past = now
    
    if flg == True and 0 < cnt:
        res += 1
    #print("Reach edge: ", res)
    if S[0] == "L":
        #print(0, ": edge BAD")
        res -= 1
        if 0 < cnt and ("R" in S) :
            #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: Accepted

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
    cnt2= 0
    if N == 1:
        return print(0)
    if N == 2:
        if (S[0] == "R" and S[1] == "L") or (S[0] == "L" and S[1] == "R"):
            if 0 < cnt:
                return print(1)
            else:
                return print(0)
        
        if (S[0] == "R" and S[1] == "R") or (S[0] == "L" and S[1] == "L"):
            return print(1)
    
    flg = False
    for n in range(1, N):
        now = S[n]
        #print(past, now, res)
        if past == "R" and now == "L":
            #print(n, ": BAD")
            res -= 2
            flg = True
        if past == "L" and now == "R" and flg == True:
            if 0 < cnt:
                #print("reverse")
                res += 2
                cnt -= 1
                cnt2 += 1
            flg = False
        past = now
    
    if flg == True and 0 < cnt:
        res += 1
    #print("Reach edge: ", res)
    if S[0] == "L":
        #print(0, ": edge BAD")
        res -= 1
        if 0 < cnt and ("R" in S) :
            #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: 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(n-1, cnt+2*k))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
s = input() #LRLRRL 群の数5 = 区切りの数4 + 1

cnt = s.count('RL') + s.count('LR')
change = min(cnt, K) # 挙げられる幸福度がK以上でないか

ans = N - (cnt + 1) + 2 * change # 幸福な人間+改善
print(min( N-1 , ans )) # 最高でもRRRRで端の人は不幸

Submission status: Accepted

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

count = 0

if N == 1:
    print(0)
    sys.exit()
else:
    for n in range(1, N - 1):
        if S[n] == 'R':
            if S[n + 1] == S[n]:
                count += 1
        elif S[n] == 'L':
            if S[n - 1] == S[n]:
                count += 1

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

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

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

#評価
res = 0
for i in range(N):
    if S[i] == "L":
        if i == 0:
            continue
        if S[i-1] == "L":
            res += 1
    if S[i] == "R":
        if i == N-1:
            continue
        if S[i+1] == "R":
            res += 1
#K回の操作
for _ in range(K):
    if res < N-2:
        res += 2
    elif res == N-2:
        res += 1
    else:
        break
print(res)

Submission status: Accepted

Solution code:
from collections import Counter
mod = 1000000007


def inverse(a):
    return pow(a, mod - 2, mod)


def usearch(x, a):
    lft = 0
    rgt = len(a) + 1
    while rgt - lft > 1:
        mid = (rgt + lft) // 2
        if a[mid] <= x:
            lft = mid
        else:
            rgt = mid
    return lft


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

main()

Submission status: Accepted

Solution code:
from collections import Counter
mod = 1000000007


def inverse(a):
    return pow(a, mod - 2, mod)


def usearch(x, a):
    lft = 0
    rgt = len(a) + 1
    while rgt - lft > 1:
        mid = (rgt + lft) // 2
        if a[mid] <= x:
            lft = mid
        else:
            rgt = mid
    return lft


def main():
    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 = n - 1 - cnt
    while cnt >= 2 and k > 0:
        ans += 2
        cnt -= 2
        k -= 1

    if k > 0 and cnt > 0:
        ans += 1

    print(ans)

main()

Submission status: Accepted

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

ans = N - 1 - s.count('RL') - s.count('LR')
print(min( N-1 , ans + 2 * K ))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
L = list(input())
L.insert(0, '')
L.append('')
num = 0
for n in range(1, N+1):
    if L[n] == 'L' and L[n - 1] == 'L':
        num += 1
    if L[n] == 'R' and L[n + 1] == 'R':
        num += 1
ans = min(num + K * 2, N - 1)
print(str(ans))

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

Submission status: Accepted

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

i = 0
counter = 1
assyuku = [1]
while i+counter < n:
    if s[i] == s[i+counter]:
        assyuku[-1] += 1
        counter += 1
    else:
        assyuku.append(1)
        i += counter
        counter = 1
assyuku = [x-1 for x in assyuku]
if len(assyuku) > k*2:
    print(sum(assyuku)+2*k)
else:
    print(n-1)

Submission status: Accepted

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

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

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

Submission status: Accepted

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

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

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

Submission status: Accepted

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

seqCnt = 0
seqTotal = 0
for i in range(n-1) :
    #print(i, seqCnt)
    if s[i] == s[i+1] :
        seqCnt += 1
    if s[i] != s[i+1] or i == n - 2 :
        #print(ans, seqCnt, i)
        seqTotal += seqCnt
        seqCnt = 0

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
l=list(input())
m=0
if n==1:
  print(0)
else:
  for i in range(1,n-1):
    if l[i]=="R":
      if l[i+1]=="R":
        m+=1
    if l[i]=="L":
      if l[i-1]=="L":
        m+=1
  if l[0]=="R" and l[0]==l[1]:
    m+=1
  if l[-1]=="L" and l[-2]==l[-1]:
    m+=1
  print(min(m+k*2,n-1))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
prev = None
ori = 0
change = 0
for i in range(N):
    if S[i] == prev:
        ori += 1
    elif i != 0:
        change += 1
    prev = S[i]
print(min(ori + change, ori + 2*K))

Submission status: Accepted

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: Accepted

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: Accepted

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

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=list(input())
point=s[0]
count=0
while k!=0 and count!=n:
    if s[count]!=point:
        while True:
            if count==n:break
            elif s[count]!=point:
                s[count]=point
                count +=1
            else:break
        k -=1
    else:count +=1

#print("".join(s))
ans=0
for i in range(n-1):
    if s[i]==s[i+1]:
        ans +=1
print(ans)

Submission status: Accepted

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

a = []
temp = S[0]
s = []
ans = 0

if len(S) > 1 and temp == S[1]:
    hantei = True
    a.append(temp)
else:
    hantei = False
    s.append(list(S[0]))

for i in range(1, N):
    if temp == S[i]:
        ans += 1
    if hantei and temp != S[i]:
        s.append(a)
        a = []
        hantei = False
    if temp != S[i] or hantei:
        hantei = True
        a.append(S[i])
        temp = S[i]
if len(S) > 1:
    s.append(a)

length = len(s)
for i in range(K):
    if length > 2:
        ans += 2
        length -= 2
    elif length == 2:
        ans += 1
        break

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

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

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

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
N, K = map(int,input().split())
S = input()
group_size = 1
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: Accepted

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

L_cnt = S.count('L')
R_cnt = S.count('R')

new_S = S.replace('LR','L,R').replace('RL','R,L')
split_S = new_S.split(',')

happiness = max_happiness - new_S.count(',')

happiness = happiness + K*2

print(min(happiness,max_happiness))

Submission status: Accepted

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 len(Llist) != len(Rlist):
            ans += 2
        else:
            if length == 0:
                ans += 1
            else:
                ans += 2
    print(ans)

Submission status: Accepted

Solution code:
#abc140c

n,k=map(int,raw_input().split())
s=raw_input()
cnt=s.count('LR')+s.count('RL')+1
res=n-max(1,cnt-k*2)
print res

Submission status: Accepted

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

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

Submission status: Accepted

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) <=1):
        break
    if(len(ss) >2):
        ss.pop()
        ss.pop()
        score+=2
    else:
        ss.pop()
        score+=1


print(score)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import sys
import math
from copy import deepcopy
from collections import deque, defaultdict
from operator import mul
from functools import reduce
sys.setrecursionlimit(20000000)

# input = sys.stdin.readline


def main():
    n, k = map(int, input().split())
    s = input()
    s = s + 'g'

    happiness = 0

    for i in range(len(s) - 1):
        if s[i] == s[i+1]:
            happiness += 1

    ans = []
    last_one = s[0]
    tmp = []

    for s in s:
        if s != last_one:
            ans.append(tmp)
            tmp = []

        tmp.append(s)
        last_one = s

    if len(ans) - 1 > k * 2:
        print(happiness + (k * 2))
    else:
        print(happiness + len(ans) - 1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N,K = (int(i) for i in input().split())
S = list(input())

cnt = 0
x = 1
tmp = S[0]
while cnt < K and x <= N-1:
    if S[x] != tmp:
        S[x] = tmp
        x += 1
        if x > N-1:
            break
        while S[x] != tmp and x <= N-1:
            S[x] = tmp
            x += 1
            if x > N-1:
                break
        cnt += 1
        if x > N-1:
            break

    else:
        x += 1


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

print(ans)

Submission status: Accepted

Solution code:
# ABC140D - Face Produces Unhappiness
def main():
    # change a part properly -> +2
    N, K = tuple(map(int, input().split()))
    S = input().rstrip()
    ans = min(N - 1, sum(i == j for i, j in zip(S, S[1:])) + K * 2)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

ans = 0
for x,y in zip(S,S[1:]):
    if x==y:
        ans += 1

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