Problem:


Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.



Sample input:
5 1
00010


Sample output:
4

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
S = input()
new_S = []
count_S = []

cur_c = S[0]
cur_count = 0

new_S.append(cur_c)
for c in S:
    if c == cur_c:
        cur_count += 1
    else:
        new_S.append(c)
        count_S.append(cur_count)
        cur_count = 1
        cur_c = c
count_S.append(cur_count)        

new_count = []
st_ix = 0
if S[0] == '0':
    cur_sum = sum(count_S[:2*K])
    st_ix = 1
    new_count.append(cur_sum)
else:
    cur_sum = sum(count_S[:2*K+1])
    new_count.append(cur_sum)

en_ix = st_ix + 2*K + 1
cur_sum = sum(count_S[st_ix:en_ix])
new_count.append(cur_sum)

while en_ix < len(count_S):
    # shift st_ix
    st_ix = st_ix + 2
    en_ix = en_ix + 2
    cur_sum -= (count_S[st_ix-2] + count_S[st_ix-1])
    cur_sum += (count_S[max(en_ix-2, len(count_S)]
                        + count_S[max(en_ix-1, len(count_S)])
    new_count.append(cur_sum)

print(max(new_count))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
S = input()
new_S = []
count_S = []

cur_c = S[0]
cur_count = 0

new_S.append(cur_c)
for c in S:
    if c == cur_c:
        cur_count += 1
    else:
        new_S.append(c)
        count_S.append(cur_count)
        cur_count = 1
        cur_c = c
count_S.append(cur_count)
        

new_count = []
st_ix = 0
maxlen_ix = len(count_S)-1
if S[0] == '0':
    cur_sum = sum(count_S[:min(2*K, maxlen_ix)])
    st_ix = 1
    new_count.append(cur_sum)

else:
    cur_sum = sum(count_S[:max(2*K+1, maxlen_ix)])
    new_count.append(cur_sum)

en_ix = st_ix + 2*K + 1
cur_sum = sum(count_S[st_ix:max(en_ix, maxlen_ix)])
new_count.append(cur_sum)
while en_ix < len(count_S):
    # shift st_ix
    st_ix = st_ix + 2
    en_ix = en_ix + 2
    cur_sum -= (count_S[st_ix-2] + count_S[st_ix-1])
    cur_sum += (count_S[en_ix-2] + count_S[en_ix-1])
    new_count.append(cur_sum)

print(max(new_count))

Submission status: Runtime Error

Solution code:
from itertools import accumulate

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

nums = []
tmp = "1" #はじめに0が入ったら、0からスタートというのがわかる。
count = 0
for s in S:
    if tmp == s:
        count += 1
    else:
        nums.append(count)
        count = 1
        tmp = s
nums.append(count)

# print(nums)
# 累積和表示にする(listって足し算できるのね)
# これによって、各文字最初の値が明らかになる
acc = [0]+list(accumulate(nums))
# print(acc)
n = len(nums)
w = min(2*K + 1)

ans = 0
for i in range(0,n-w+1,2): #2個飛ばし
    ans = max(ans,acc[i+w]-acc[i])
print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
S = input()
new_S = []
count_S = []

cur_c = S[0]
cur_count = 0

new_S.append(cur_c)
for c in S:
    if c == cur_c:
        cur_count += 1
    else:
        new_S.append(c)
        count_S.append(cur_count)
        cur_count = 1
        cur_c = c
count_S.append(cur_count)
        

new_count = []
st_ix = 0
if S[0] == '0':
    cur_sum = sum(count_S[:2*K])
    st_ix = 1
    new_count.append(cur_sum)

else:
    cur_sum = sum(count_S[:2*K+1])
    new_count.append(cur_sum)

en_ix = st_ix + 2*K + 1
cur_sum = sum(count_S[st_ix:en_ix])
new_count.append(cur_sum)
while en_ix < len(count_S):
    # shift st_ix
    st_ix = st_ix + 2
    en_ix = en_ix + 2
    cur_sum -= (count_S[st_ix-2] + count_S[st_ix-1])
    cur_sum += (count_S[en_ix-2] + count_S[en_ix-1])
    new_count.append(cur_sum)

print(max(new_count))

Submission status: Runtime Error

Solution code:
a = 0
right = 0
left = 0
g = 0
su = 0
if A[0] == 0:
    for i in range(len(s)):
        su +=s[right]
        if right%2==0:
            g += 1
        right +=1
        if g<=K:
            a = max(a,su)
        else:
            while g>K:
              su -= s[left]
              if left%2==0:
                  g -=1
              left +=1
        a = max(a,su)
else:
    for i in range(len(s)):
        su +=s[right]
        if right%2==1:
            g += 1
        right +=1
        if g<=K:
            a = max(a,su)
        else:
            while g>K:
              su -= s[left]
              if left%2==1:
                  g -=1
              left +=1
        a = max(a,su)
print(a)

Submission status: Runtime Error

Solution code:
import collections
n, k = map(int, input().split())
s = [int(i) for i in input()]
c = []
prv = 1
cnt = 0
for i in s:
    if prv != i:
        c.append(cnt)
        cnt = 1
        prv = i
    else:
        cnt += 1
if cnt > 0:
    c.append(cnt)
if prv == 0:
    c.append(0)
que = collections.deque(c[0])
res =c[0]
ans = c[0]
m = len(c) // 2
for i in range(m):
    if len(que) == 2*k + 1:
        res -= que.popleft() + que.popleft()
    que.append(c[2*i +1])
    que.append(c[2*i +2])
    res += c[2*i+1] + c[2*i+2]
    ans = max(res, ans)
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
N,K = list(map(int,input().split()))
A = input()
A = list(A)
A = list(map(int,A))
l = [0]
s = []

for i in range(N-1):
    if A[i] != A[i+1]:
        l.append(i+1)
        s.append(l[len(l)-1]-l[len(l)-2])
l.append(N)
s.append(l[len(l)-1]-l[len(l)-2])
a = 0
right = 0
left = 0
g = 0
su = 0
if A[0] == 0:
    for i in range(len(s)):
        su +=s[right]
        if right%2==0:
            g += 1
        if g<=K:
            a = max(a,su)
            right +=1
        else:
            while g>K:
              su -= s[left]
              if left%2==0:
                  g -=1
              left +=1
else:
    for i in range(len(s)):
        su +=s[right]
        if right%2==1:
            g += 1
        if g<=K:
            a = max(a,su)
            right +=1
        else:
            while g>K:
              su -= s[left]
              if left%2==1:
                  g -=1
              left +=1
print(a)

Submission status: Runtime Error

Solution code:
N,K = (int(i) for i in input().split())
K += 2 #とれる範囲
S = input()
S = [s for s in S]
cnt = []
last = S[0]
c = 0

for s in S:
    if s == last:
        c += 1
    else:
        cnt.append(c)
        c = 1
        last = s

cnt.append(c)
cnt.extend([0,0,0])
hold = sum([cnt[n] for n in range(K+1)])
ans = [hold]
for i in range(1,len(cnt)-K):
    #right => cnt[i-1]
    #left => cnt[i+K]
    ans.append(hold-cnt[i-1]+cnt[i+K])
    hold = sum([cnt[n+i] for n in range(K+1)])
print(max(ans))

Submission status: Runtime Error

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

change_flg = False
cnt = 0
ilands = []


def cumsum(array):
    value = array[0]
    results = [value] * len(array)
    for index, elm in enumerate(array[1:], 1):
        value += elm
        results[index] = value
    return results


def change():
    global cnt, change_flg
    ilands.append(cnt)
    cnt = 0
    change_flg = not change_flg

for value in s:
    if value: # case 1 cnt
        if change_flg:
            change()
    else: # case 0 cnt : plus
        if not change_flg:
            change()
    cnt += 1

ilands.append(cnt)

ilands += [0] * 10**5

if not len(ilands) % 2:
    ilands.append(0)

merged = list(cumsum(ilands))
section = 2 * k + 1

results = [0] * (len(ilands) // 2 - (k - 1))

merged.append(0)
for i in range(len(results)):
    start = i * 2 - 1
    results[i] = merged[start + section] - merged[start]

print(max(results))

Submission status: Runtime Error

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

change_flg = False
cnt = 0
ilands = []


def cumsum(array):
    value = array[0]
    results = [value] * len(array)
    for index, elm in enumerate(array[1:], 1):
        value += elm
        results[index] = value
    return results


def change():
    global cnt, change_flg
    ilands.append(cnt)
    cnt = 0
    change_flg = not change_flg

for value in s:
    if value: # case 1 cnt
        if change_flg:
            change()
    else: # case 0 cnt : plus
        if not change_flg:
            change()
    cnt += 1

ilands.append(cnt)

if len(ilands) <= k:
    print(n)
    exit()

if not len(ilands) % 2:
    ilands.append(0)

merged = list(cumsum(ilands))
section = 2 * k + 1

results = [0] * (len(ilands) // 2 - (k - 1))

merged.append(0)
for i in range(len(results)):
    start = i * 2 - 1
    results[i] = merged[start + section] - merged[start]

print(max(results))

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
S = input()
L = [0]
res = '1'
i = 0
for s in S:
    if s != res:
        L.append(i)
        i += 1
    else:
        i += 1
    res = s
L.append(i)
if len(L)<=2*k+1:
    ans = N
for i in range(0,len(L)-k*2-2,2):
    ans = L[i+K*2+1]-L[i]
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
n, k = map(int, input().split())
s = list(map(lambda x: x == "1", list(input())))


def p(value, *args, **kwargs):
    print(*map(int, value), *args, **kwargs)

# ---
change_flg = False
cnt = 0
ilands = []


def change():
    global cnt, change_flg
    ilands.append(cnt)
    cnt = 0
    change_flg = not change_flg

for value in s:
    if value: # case 1 cnt
        if change_flg:
            change()
    else: # case 0 cnt : plus
        if not change_flg:
            change()
    cnt += 1

ilands.append(cnt)

if len(ilands) <= k:
    print(n)
    exit()

if not len(ilands) % 2:
    ilands.append(0)

merged = list(np.cumsum(ilands))
section = 2 * k + 1

results = [0] * (len(ilands) // 2 - (k - 1))

merged.append(0)
for i in range(len(results)):
    start = i * 2 - 1
    results[i] = merged[start + section] - merged[start]
#     print(start, section + start, merged[section + start], merged[start])
# 
# print(ilands)
# print(merged)
# print(results, len(ilands) // 2 - (k - 1))

print(max(results))

Submission status: Runtime Error

Solution code:
N,K = (int(i) for i in input().split())
K += 1
S = input()
S = [s for s in S]
cnt = []
last = S[0]
c = 0

for s in S:
    if s == last:
        c += 1
    else:
        cnt.append(c)
        c = 1
        last = s

cnt.append(c)
hold = sum([cnt[n] for n in range(K)])
ans = [hold]
for i in range(1,len(cnt)-K):
    ans.append(hold-cnt[i]+cnt[i+K])
    hold = hold-cnt[i]+cnt[i+K]

print(max(ans))

Submission status: Runtime Error

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

print(a)


if s[-1]=='0':
	m=2*k
else:
	m=2*k+1
if n<m or len(a)-m-1<0:
	print(n)
elif len(a)==2 and s[0]=='1' and k==0:
	print(0)
else:
	print(n)
else:
	_max=0
	i=len(a)-1
	while i-m>=0:
		tmp=a[i]-a[i-m]
		#print('i:{} tmp:{}'.format(i,tmp))
		if tmp>_max:
			_max=tmp
		i-=1
	print(_max)

Submission status: Runtime Error

Solution code:
N,K = (int(i) for i in input().split())
K += 1
S = input()
S = [s for s in S]
cnt = []
last = S[0]
c = 0

for s in S:
    if s == last:
        c += 1
    else:
        cnt.append(c)
        c = 1
        last = s

cnt.append(c)
print(cnt)
hold = sum([cnt[n] for n in range(K)])
ans = [hold]
for i in range(1,len(cnt)-K):
    ans.append(hold-cnt[i]+cnt[i+K])
    hold = hold-cnt[i]+cnt[i+K]

print(max(ans))

Submission status: Runtime Error

Solution code:
import itertools

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

# list of run-length
runlen = [len(list(g)) for k, g in itertools.groupby(S)]

# runlen starts and ends with the length of a run of '1'
if S[0] == '0':
    runlen = [0] + runlen
if S[-1] == '0':
    runlen = runlen + [0]

# list of sum of runlen[i : i + k]
k = 2 * K + 1
sublen = [sum(runlen[i : i + k]) for i in range(0, N - k, 2)]

print(max(sublen))

Submission status: Runtime Error

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

#print(a)

if len(a)==2:
	print(a[1])
else:
	if s[0]=='0':
		m=2*k
	else:
		m=2*k+1
	if m>len(s):
		print(len(s))
	else:
		_max=a[m]
		i=1
		while m+i<len(a):
			tmp=a[i+m]-a[i]
			#print(tmp)
			if tmp>_max:
				_max=tmp
			i+=1
		print(_max)

Submission status: Runtime Error

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

#print(a)

if len(a)==2:
	print(a[1])
else:
	if s[0]=='0':
		m=2*k
	else:
		m=2*k+1
	if m>len(s):
		print(len(s))
	else:
		_max=a[m]
		i=1
		while m+i<len(a):
			tmp=a[i+m]-a[i]
			print(tmp)
			if tmp>_max:
				_max=tmp
			i+=1
		print(_max)

Submission status: Runtime Error

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

#print(a)

if len(a)==2:
	print(a[1])
else:
	if s[-1]=='0':
		m=2*k
	else:
		m=2*k+1
	_max=a[m]
	i=len(a)-1
	while i-m>=0:
		tmp=a[i]-a[i-m]
		#print('i:{} tmp:{}'.format(i,tmp))
		if tmp>_max:
			_max=tmp
		i-=1
	print(_max)

Submission status: Runtime Error

Solution code:
n, k = map(int,input().split())
s = input()
cs = []
cnt = 1
for i in range(1,n):
  if s[i] == s[i-1]:
    cnt += 1
    if i == n-1:
      cs.append(cnt)
  elif s[i] != s[i-1]:
    cs.append(cnt)
    cnt = 1
#print(cs)
l = [0]
for j in range(len(cs)):
  l.append(l[j]+cs[j])
#print(l)
ans = []
for c in range(0,len(l)-2*k,2):
  if s[0] == '1':
    ans.append(l[2*k+c+1]-l[c])
  else:
    ans.append(l[2*k+c]-l[c])
print(max(ans))

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
S = input()+'2'
L = []
if S[0] == '0':
    L.append(1)
for i in range(1,N):
    if S[i] != S[i+1]:
        L.append(i+1)
for i in range(0,len(L)-K*2,2):
    ans = L[i+K*2]-(L[i]-1)#L[i-1]?
ans = 1 if N == 1 else ans
ans = 3 if N == 3 else ans
ans = 2 if N == 2 or S == '010' else ans
print(ans)

Submission status: Runtime Error

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

#print(a)

if len(a)==2:
	print(a[1])
else:
	if s[0]=='0':
		m=2*k
	else:
		m=2*k+1
	_max=a[m]
	i=1
	while m+i<len(a):
		tmp=a[i+m]-a[i]
		print(tmp)
		if tmp>_max:
			_max=tmp
		i+=1
	print(_max)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = str(input())
Sb = []
zero = 0
for i in range(n):
  if int(s[i]):
    if len(Sb) == 0 or Sb[-1][0] == 0:
      Sb.append([1, 1])
    else:
      Sb[-1][1] += 1
  else:
    if len(Sb) == 0 or Sb[-1][0]:
      Sb.append([0, 1])
      zero += 1
    else:
      Sb[-1][1] += 1
if zero <= k:
  print(n)
else:
  if Sb[0][0] != 1:
    Sb.insert(0, [1, 0])
  if Sb[-1][0] != 1:
    Sb.append([1, 0])
  tmp = ans
  for i in range(zero - k):
    tmp += Sb[2 * k + 2 * (i+1)][1] + Sb[2 * k + 2 * (i+1) - 1][1] - Sb[2 * i][1] - Sb[2 * i + 1][1]
    ans = max(ans, tmp)
  print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**10) 
N,K = list(map(int,input().split()))
A = input()
A = list(A)
A = list(map(int,A))
def serch_right(x,K,t):
    global count0,count1
    if x<0 or len(A)<=x:
        return count1
    if A[x]==0:
        if t == 0:
            t=0
            count1 +=1
        elif t==1 :
            if count0==K:
                return count1
            t=0
            count1 +=1
            count0 +=1

    else:
        t=1
        count1+=1
    count1 = serch_right(x+1,K,t)
    return count1
def serch_left(x,A):
    global count2
    if x<0 or len(A)<=x or A[x]==0:
        return count2
    if A[x]==1:
        count2 +=1
    count2 = serch_left(x-1,A)     
    return count2
count =0
count0 =0
count1 =0
for i in range(len(A)):
    if A[i]==0 and (A[i-1]!=0 or i == 0):
        count2 = 0
        count1 =0
        count0 =0
        t = 1
        count1 = serch_right(i,K,t)
        count2 = serch_left(i-1,A)
        count1 = count1 + count2
        count = max(count1,count)
print(max(count,1))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**10) 
N,K = list(map(int,input().split()))
A = input()
A = list(A)
A = list(map(int,A))
def serch_right(x,K,t):
    global count0,count1
    if x<0 or len(A)<=x:
        return count1
    if A[x]==0:
        if t == 0:
            t=0
            count1 +=1
        elif t==1 :
            if count0==K:
                return count1
            t=0
            count1 +=1
            count0 +=1
            
    else:
        t=1
        count1+=1
    count1 = serch_right(x+1,K,t)
    return count1
def serch_left(x,A):
    global count2
    if x<0 or len(A)<=x or A[x]==0:
        return count2
    if A[x]==1:
        count2 +=1
    count2 = serch_left(x-1,A)     
    return count2
count =0
count0 =0
count1 =0
for i in range(len(A)):
    if A[i]==0 and (A[i-1]!=0 or i == 0):
        count2 = 0
        count1 =0
        count0 =0
        t = 1
        count1 = serch_right(i,K,t)
        count2 = serch_left(i-1,A)
        count1 = count1 + count2
        count = max(count1,count)
print(max(count,1))

Submission status: Runtime Error

Solution code:
N,K = list(map(int,input().split()))
sys.setrecursionlimit(10**10) 
A = input()
A = list(A)
A = list(map(int,A))
def serch_right(x,K,t):
    global count0,count1
    if x<0 or len(A)<=x:
        return count1
    if A[x]==0:
        if t == 0:
            t=0
            count1 +=1
        elif t==1 :
            if count0==K:
                return count1
            t=0
            count1 +=1
            count0 +=1
            
    else:
        t=1
        count1+=1
    count1 = serch_right(x+1,K,t)
    return count1
def serch_left(x,A):
    global count2
    if x<0 or len(A)<=x or A[x]==0:
        return count2
    if A[x]==1:
        count2 +=1
    count2 = serch_left(x-1,A)     
    return count2
count =0
count0 =0
count1 =0
for i in range(len(A)):
    if A[i]==0 and (A[i-1]!=0 or i == 0):
        count2 = 0
        count1 =0
        count0 =0
        t = 1
        count1 = serch_right(i,K,t)
        count2 = serch_left(i-1,A)
        count1 = count1 + count2
        count = max(count1,count)
print(max(count,1))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
s=input()
a=[]
tmp=1
for i in range(len(s)-1):
	if s[i] == s[i+1]:
		tmp+=1
	else:
		a.append(tmp)
		tmp=1
a.append(tmp)

b=[]
if s[0]=='0':
	m=2*k
else:
	m=2*k+1
for i in range(len(a)-k):
	b.append(sum(a[i:i+m]))
print(max(b))

Submission status: Runtime Error

Solution code:
from itertools import groupby

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

indexes = []
counts = []
for key, group in groupby(S):
    indexes.append(int(key))
    counts.append(len(list(group)))

candidates = []
for i in range(len(indexes) - 2 * K + 1):
    if indexes[i] == 0:
        candidates.append(sum(counts[i: (i + 2 * K)]))
    elif indexes[i] == 1:
        candidates.append(sum(counts[i: (i + 2 * K + 1)]))
print(max(candidates))

Submission status: Runtime Error

Solution code:
N,k = map(int,input().split())
S = input()
lenth = 0
AllLen =[]
preS0,preS1 = S.split('1'),S.split('0')
S0 = [i for i in preS0 if i != '']
S1 = [i for i in preS1 if i != '']
num0 = k
if len(S0) <= k:
	print(len(S))
	exit() 
if S[0] == '0':
	J = k
else:J = k + 1
FirstLen = sum([len(S0[i]) for i in range(k)]) + sum([len(S1[j]) for j in range(J)])
AllLen.append(FirstLen)
CheckLen = FirstLen
if S[0] == '1' and S[-1] == '1':
    for i in range(len(S0) - k):
	    CheckLen = CheckLen - len(S0[i]) - len(S1[i]) + len(S0[i + k]) + len(S1[i + k + 1])
	    AllLen.append(CheckLen)
if S[0] == '0' and S[-1] == '1':
	CheckLen = CheckLen - len(S0[0]) + len(S0[k]) + len(S1[k])
	AllLen.append(CheckLen)
	for i in range(len(S0) - k - 1):
		CheckLen = CheckLen - len(S0[i + 1]) - len(S1[i + 1]) + len(S0[i + k + 1]) + len(S1[i + k + 2])
		AllLen.append(CheckLen)
if S[0] == '1' and S[-1] == '0':
	for i in range(len(S0) - k - 1):
		CheckLen = CheckLen - len(S0[i]) - len(S1[i]) + len(S0[i + k]) + len(S1[i + k + 1])
		AllLen.append(CheckLen)
	CheckLen = CheckLen - len(S0[len(S0) - k - 1]) - len(S1[len(S0) - k - 1]) + len(S0[len(S0) - 1])
	AllLen.append(CheckLen)
if S[0] == '0' and S[-1] == '0':
	if len(S1) == 1:
		print(len(max(S0)) + len(S1[0]))
		exit()
	CheckLen = CheckLen - len(S0[0]) + len(S0[k]) + len(S1[k])
	AllLen.append(CheckLen)
	for i in range(len(S0) - k - 2):
		CheckLen = CheckLen - len(S0[i + 1]) - len(S1[i + 1]) + len(S0[i + k + 1]) + len(S1[i + k + 1])
		AllLen.append(CheckLen)
	CheckLen = CheckLen - len(S0[len(S0) - k - 1]) - len(S1[len(S0) - k - 1]) + len(S0[len(S0) - 1])
	AllLen.append(CheckLen)
print(max(AllLen))

Submission status: Runtime Error

Solution code:
N,k = map(int,input().split())
S = input()
lenth = 0
AllLen =[]
preS0,preS1 = S.split('1'),S.split('0')
S0 = [i for i in preS0 if i != '']
S1 = [i for i in preS1 if i != '']
num0 = k
if len(S0) <= k:
	print(len(S))
	exit() 
if S[0] == '0':
	J = k
else:J = k + 1
FirstLen = sum([len(S0[i]) for i in range(k)]) + sum([len(S1[j]) for j in range(J)])
AllLen.append(FirstLen)
CheckLen = FirstLen
if S[0] == '1' and S[-1] == '1':
    for i in range(len(S0) - k):
	    CheckLen = CheckLen - len(S0[i]) - len(S1[i]) + len(S0[i + k]) + len(S1[i + k + 1])
	    AllLen.append(CheckLen)
if S[0] == '0' and S[-1] == '1':
	CheckLen = CheckLen - len(S0[0]) + len(S0[k]) + len(S1[k])
	AllLen.append(CheckLen)
	for i in range(len(S0) - k - 1):
		CheckLen = CheckLen - len(S0[i + 1]) - len(S1[i + 1]) + len(S0[i + k + 1]) + len(S1[i + k + 2])
		AllLen.append(CheckLen)
if S[0] == '1' and S[-1] == '0':
	for i in range(len(S0) - k - 1):
		CheckLen = CheckLen - len(S0[i]) - len(S1[i]) + len(S0[i + k]) + len(S1[i + k + 1])
		AllLen.append(CheckLen)
	CheckLen = CheckLen - len(S0[len(S0) - k - 1]) - len(S1[len(S0) - k - 1]) + len(S0[len(S0) - 1])
	AllLen.append(CheckLen)
if S[0] == '0' and S[-1] == '0':
	if len(S1) == 1:
		print(len(max(S0)) + len(S1[0]))
		exit()
	CheckLen = CheckLen - len(S0[0]) + len(S0[k]) + len(S1[k])
	AllLen.append(CheckLen)
	for i in range(len(S0) - k - 2):
		CheckLen = CheckLen - len(S0[i + 1]) - len(S1[i + 1]) + len(S0[i + k + 1]) + len(S1[i + k + 1])
		AllLen.append(CheckLen)
	CheckLen = CheckLen - len(S0[len(S0) - k - 1]) - len(S1[len(S0) - k - 1]) + len(S0[len(S0) - 1])
	AllLen.append(CheckLen)
print(max(AllLen))
print(AllLen)

Submission status: Runtime Error

Solution code:
N,K = [int(x) for x in input().split()]
S = input()
list = []
count = 1
for x in range(N):
    if x >= N - 1:
        list.append(count)
        break
    if S[x] == S[x+1]:
        count += 1
    else:
        list.append(count)
        count = 1
l = len(list)
max = 0
if S[0] == "1":
    start = 0
else:
    start = 1
    max = list[0] + list[1]

for x in range(start,l,2):
    number = 0
    for y in range(2*K+1):
        if x + y >= l:
            break
        else:
            number += list[x + y]
    if number > max:
        max = number
print(max)

Submission status: Runtime Error

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

#s = "0001111011110"
#n, k = len(s), 1

s="1"+s

k_pt = 0
cur_tail = 0
for cur in range(1, n):

  cur_tail+=1

  if  s[cur-1] == '1' and s[cur] == '0':
    k_pt+=1

  if  s[cur_tail-1] == '0' and s[cur_tail] == '1':
    k_pt-=1

  if k_pt <= k:
      cur_tail-=1

print(cur-cur_tail)

Submission status: Runtime Error

Solution code:
N,K = list(map(int,input().split()))
A = input()
A = list(A)
A = list(map(int,A))
def serch_right(x,K,t):
    global count0,count1
    if x<0 or len(A)<=x:
        return count1
    if A[x]==0:
        if t == 0:
            t=0
            count1 +=1
        elif t==1 :
            if count0==K:
                return count1
            t=0
            count1 +=1
            count0 +=1
            
    else:
        t=1
        count1+=1
    count1 = serch_right(x+1,K,t)
    return count1
def serch_left(x,A):
    global count2
    if x<0 or len(A)<=x or A[x]==0:
        return count2
    if A[x]==1:
        count2 +=1
    count2 = serch_left(x-1,A)     
    return count2
count =0
count0 =0
count1 =0
for i in range(len(A)):
    if A[i]==0 and (A[i-1]!=0 or i == 0):
        count2 = 0
        count1 =0
        count0 =0
        t = 1
        count1 = serch_right(i,K,t)
        count2 = serch_left(i-1,A)
        count1 = count1 + count2
        count = max(count1,count)
print(max(count,1))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)


def read_int():
    return int(input())


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, K, S):
    s1 = list(map(lambda x: len(x), filter(lambda x: x != '', S.split('0'))))
    s0 = list(map(lambda x: len(x), filter(lambda x: x != '', S.split('1'))))

    if S[0] == '0':
        s1.insert(0, 0)
    if S[-1] == '0':
        s1.append(0)

    q = deque()
    q.append(s1.pop())
    q.append(s0.pop())
    q.append(s1.pop())
    tmp = sum(q)
    ans = tmp
    while s1 or s0:
        if len(q) >= 2*K + 1:
            tmp -= q.popleft()
            tmp -= q.popleft()
        q.append(s0.pop())
        tmp += q[-1]
        q.append(s1.pop())
        tmp += q[-1]
        ans = max(ans, tmp)

    return ans


def main():
    N, K = read_int_n()
    S = read_str()
    print(slv(N, K, S))

    # N = 20
    # K = random.randint(1, 10)
    # S = ''.join(random.choices('01', k=N))
    # rS = ''.join(['0' if c == '1' else '1' for c in S])
    # print(max(slv(N, K, S), slv(N, K-1, rS)))

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys

N, K = [int(x) for x in input().split()] # N:Sの長さ K:操作を行える回数の最大値
S = [int(x) for x in list(input())] # S:0と1から成る列
index = [0] # index:Sにおいて0と1が切り替わる部分の添字を集めたリスト
length = [0] # length:1が連続して並んでいる長さの最大値の候補を集めたリスト
zeros = 0 # zeros:Sにおいて0が連続して並んでいる箇所がいくつあるか

for i in range(0, len(S) - 1): # indexの要素を取得
    if S[i] != S[i + 1]: # 0と1の変わり目を探索
        index.append(i + 1) 

if S[0] == 0: # Sが0から始まる場合
    
    for i in range(len(index)): # zerosの値を取得
        if len(index) % 2 == 0: # indexの長さが偶数である場合
            zeros = int(len(index) / 2)
        else: # indexの長さが奇数である場合
            zeros = int((len(index) + 1) / 2) 
            
    for i in range(len(index)): # max(length)の初期値を取得
        if S[len(S) - 1] == 0: # Sが0で終わっている場合
            if i % 2 == 1:
                length.append(index[i + 1] - index[i])
        else: # Sが1で終わっている場合
            if (i % 2 ==1 and (i + 1) < len(index)):
                length.append(index[i + 1] - index[i])
            elif (i % 2 ==1 and (i + 1) == len(index)): # 最後の1の連続を処理
                length.append((len(S) - 1) - index[i] + 1)

    for i in range(len(index)): # Sのindex[i]番目を左端としたときの1の連続回数の最大値をそれぞれ求める
        if K >= zeros: # Kがzeros以上なら0の連続を全て1に置き換えて終了
            print(len(S))
            sys.exit()
        
        elif i + (2 * K) <= (len(index) + 1): # 添字が飛び出ないように注意（飛び出るようなやつはそもそも最大値の候補にならない）
            if i % 2 == 0: # 左端が0の場合
                length.append(index[(i + (2 * K) - 1) + 1] - index[i])
            else: # 左端が1の場合
                if i + (2 * K) < (len(index) - 1):
                    length.append(index[i + (2 * K) + 1] - index[i])
                elif i + (2 * K) == (len(index) - 1):
                    length.append((len(S) - 1) - index[i] + 1)
        elif (i + (2 * K) == len(index) and i % 2 == 1):
            length.append(len(S) - index[i])
                
                
    print(max(length))
    sys.exit()

else: # Sが1から始まる場合
    
    for i in range(len(index)): # zerosの値を取得
        if len(index) % 2 == 0: # indexの長さが偶数である場合
            zeros = int(len(index) / 2)
        else: # indexの長さが奇数である場合
            zeros = int((len(index) - 1) / 2) 
            
    for i in range(len(index)): # max(length)の初期値を取得
        if S[len(S) - 1] == 0: # Sが0で終わっている場合
            if i % 2 == 0:
                length.append(index[i + 1] - index[i])
        else: # Sが1で終わっている場合
            if (i % 2 ==0 and (i + 1) < len(index)):
                length.append(index[i + 1] - index[i])
            elif (i % 2 ==0 and (i + 1) == len(index)): # 最後の1の連続を処理
                length.append((len(S) - 1) - index[i] + 1)

    for i in range(len(index)): # Sのindex[i]番目を左端としたときの1の連続回数の最大値をそれぞれ求める
        if K >= zeros: # Kがzeros以上なら0の連続を全て1に置き換えて終了
            print(len(S))
            sys.exit()
        
        elif i + (2 * K) <= (len(index) - 1): # 添字が飛び出ないように注意（飛び出るようなやつはそもそも最大値の候補にならない）
            if i % 2 == 0: # 左端が1の場合
                if i + (2 * K) < (len(index) - 1):
                    length.append(index[i + (2 * K) + 1] - index[i])
                elif i + (2 * K) == (len(index) - 1):
                    length.append((len(S) - 1) - index[i] + 1)
                
            else: # 左端が0の場合
                length.append(index[(i + (2 * K) - 1) + 1] - index[i])

                
    print(max(length))
    sys.exit()