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 = list(input())
d = dict() # d[poc.niza] = [dulj.niza, lijevo, desno]

niz = []
for i in range(len(s)):
    if len(niz) and niz[0] <= i <= niz[1]:
        continue
    if not int(s[i]):
        d[i] = [1]
        j = i + 1
        while j < len(s) and not int(s[j]):
            d[i][0] += 1
            j += 1
        niz = [i, j]
print(d)
for i in d:
    j = i - 1
    d[i] += [0, 0]
    while j >= 0 and int(s[j]):
        d[i][1] += 1
        j -= 1
    j = i + d[i][0]
    while j < len(s) and int(s[j]):
        d[i][2] += 1
        j += 1
print(d)
d1 = d.copy()

for i in d1:
    d1[i] = sum(d1[i])
print(d1)

key = list(d1.values())
key.sort()
sol = []

for i in range(k):
    for j in d1:
        if d1[j] == max(key):
            sol.append(j)
            key.remove(max(key))
            print(sol)
            break
        
print(s)
        
for i in sol:
    for j in range(d[i][0]):
        s[i + j] = '1'
    print(s)

niz = []
d2 = dict()

for i in range(len(s)):
    if len(niz) and niz[0] <= i <= niz[1]:
        continue
    if int(s[i]):
        d2[i] = 1
        j = i + 1
        while j < len(s) and int(s[j]):
            d2[i] += 1
            j += 1
        niz = [i, j]
        
print(max(d2.values()))

Submission status: Runtime Error

Solution code:
import numpy as np

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

l = [list(np.repeat(0, K)), list(np.repeat(0, K))]
ans = []
k = [int(s) for s in S]
v0 = 1 if k[0] == 0 else 0
v1 = 1 if k[0] == 1 else 0
for i in range(1, N):
    if (k[i]==0) & (k[i-1]==0):
        v0 += 1
    elif (k[i]==1) & (k[i-1]==0):
        l[0].append(v0)
        v0 = 0
        v1 += 1
    elif (k[i]==0) & (k[i-1]==1):
        l[1].append(v1)
        v1 = 0
        v0 += 1
        
        
        a = sum(l[0][-K:]+l[1][-K-1:])
        ans.append(a)
        
    elif (k[i]==1) & (k[i-1]==1):
        v1 += 1
        
for i, v in enumerate([v0, v1]):
    if v > 0:
        l[i].append(v)

if (v0==0) & (v1>0):
    a = sum(l[0][-K:]+l[1][-K-1:])
    ans.append(a)
    
print(max(ans))

Submission status: Runtime Error

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

arr = []
cnt = 0
comp = S[0]
for s in S:
    if s==comp:
        cnt += 1
    else:
        if comp=='0':
            arr.append(-cnt)
        else:
            arr.append(cnt)
        cnt = 1
        comp = s
if comp=='0':
    arr.append(-cnt)
else:
    arr.append(cnt)

def iter(A, cnt):
    if cnt>=K or len(A)<3:
        return max(A)
    m = -A[0]+A[1]
    args = [0]
    for i in range(len(A)-2):
        s3 = A[i] - A[i+1] + A[i+2]
        if m<s3:
            m = s3
            args = [i]
        elif m==s3:
            args.append(i)
    s3 = A[-2]-A[-1]
    if m<s3:
        m = s3
        args = [len(A)-1]
    elif m==s3:
        args.append(len(A)-1)
    cands = []
    for arg in args:
        if arg==0:
            B = [-A[0]+A[1]] + A[2:]
        elif arg==len(A)-1:
            B = A[:-2] + [A[-2]-A[-1]]
        else:
            B = A[:arg] + [A[arg] - A[arg+1] + A[arg+2]] + A[arg+3:]
        cands.append(iter(B, cnt+1))
    return max(cands)


print(iter(arr, 0))

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
S = list(map(int,input()))
blobs = []
if S[0] == 0:
    blobs.append(0)
cnt = 0
past_i = 0
for i in range(len(S)):
    if i == 0:
        past_i = S[i]
    if past_i == S[i]:
        cnt += 1
        past_i = S[i]
        
    else:
        blobs.append(cnt)
        cnt = 1
        past_i = S[i]
    if i == len(S)-1:
        blobs.append(cnt)

if S[-1] == 0:
    blobs.append(0)
print(blobs)
sums = []
for i in range(len(blobs)//2-K+1):
    temp_sum = sum(blobs[2*i:min(2*(i+K)+1,len(blobs))])
    sums.append(temp_sum)
    if temp_sum == N:
        break
print(max(sums))

Submission status: Runtime Error

Solution code:
# coding: utf-8

n, k = map(int, input().split())
s = input()
s += "2"
n += 1

nums = []
if s[0] == "0":
    nums.append(0)

fin = False
i = 0
while i < n:
    if fin:
        break
    for j in range(i, n):
        if s[j] != s[i]:
            nums.append(j-i)
            i = j
            break
        if i == n-1:
            fin = True
            break

if s[-2] == "0":
    nums.append(0)
# print(nums)
length = min([2*k+1, len(nums)])

ans = 0
for i in range(0, length):
    ans += nums[i]

oldsum = ans
for i in range(0, length, 2):
    if i + length + 1 < len(nums):
        newsum = oldsum - (nums[i] + nums[i+1]) + (nums[length+i] + nums[length+2])
        if newsum > ans:
            ans = newsum
        oldsum = newsum
    else:
        break

print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8

import sys

n, k = [int(x) for x in input().split()]
ss = [int(x) for x in input()]

zero_array = []
one_array = []
curr_num = ss[0]
flag = 0

if curr_num == 0:
    zero_array.append(0)
else:
    one_array.append(0)
    flag = 1

for i in ss:
    if curr_num == i:
        if i == 0:
            zero_array[-1] += 1
        else:
            one_array[-1] += 1
    else:
        curr_num = i
        if i == 0:
            zero_array.append(1)
        else:
            one_array.append(1)

if k >= len(zero_array):
    print(sum(zero_array) + sum(one_array))
    sys.exit()
else:
    t = 0
    tmp = sum(zero_array[t: t+k]) + sum(one_array[t: t+k+flag])
    max_count = tmp
    while t + k + flag <= len(one_array):
        if t+k+flag < len(one_array):
            tmp += zero_array[t+k] - zero_array[t] + one_array[t+k+flag] - one_array[t+flag-1]
        else:
            tmp += zero_array[t + k] - zero_array[t] - one_array[t + flag - 1]
        if tmp > max_count:
            max_count = tmp
            # print(t, max_count)
        t += 1

    print(max_count)
# print(zero_array)
# print(one_array)

Submission status: Runtime Error

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

ms = []
a1 = ''
fptrs = []
lptrs = []

flg = 0
i = 0

while i != N - 1:
	if(S[i] == '0' and flg == 0):
		fptrs.append(i)
		flg = 1
	elif(S[i]== '1' and flg == 1):
		lptrs.append(i)
		flg = 0
	else:
		pass
	i = i + 1

m = 0
fptrss = []
lptrss = []

for i in range(len(fptrs) - K + 1):
	buf_f = []
	buf_l = []
	for j in range(K):
		buf_f.append(fptrs[i+j])
		buf_l.append(lptrs[i+j])
	fptrss.append(buf_f)
	lptrss.append(buf_l)

cntbufs = []
m = 0

for fprts,lptrs in zip(fptrss,lptrss):
	bufs = []
	cntbufs = []
	for c in S:
		bufs.append(c)
	for fptr,lptr in fprts,lptrs:
		for i in range(fptr,lptr):
			bufs[i] = '1'
	bufs = ''.join(bufs)
	print(bufs)
	cntbuf = 0
	for i,c in enumerate(bufs):
		if(c == '1' and i != len(bufs) - 1):
			cntbuf = cntbuf + 1
		elif(c == '1' and i != len(bufs) - 1):
			cntbuf = cntbuf + 1
			cntbufs.append(cntbuf)
		else:
			cntbufs.append(cntbuf)
			cntbuf = 0
	if(m < max(cntbufs)):
		m = max(cntbufs)

if fptrs == []:
	m = N

print(m)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0;i<n;i++)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define SORT(c) sort((c).begin(),(c).end())

using namespace std;

inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}

//sort(v.rbegin(), v.rend(), [](auto& x, auto& y){return x[1] < y[1];});
//cout << fixed << setprecision(10) << ans << defaultfloat << endl;
typedef long long ll;
typedef vector<int> Vi;
typedef vector<ll> Vl;
typedef vector<double> Vd;
typedef vector<string> Vs;

ll mod = 1e9+7;

int main() {
    int N,K;
    cin >> N >> K;
    string S;
    cin >> S;
    Vi v;

    if (S[0]=='0') v.push_back(0);

    int c=1;
    REP(i,N-1) {
        if (S[i+1]==S[i]) {
            c++;
        }
        else {
            v.push_back(c);
            c = 1;
        }
    }
    v.push_back(c);
    if (S[N]=='0') v.push_back(0);

    //for(auto i:v) cout << i << endl;

    int l=0,r=2*K,ans=0;
    if (r+1>v.size()) {
        cout << accumulate(v.begin(),v.end(),0) << endl;
        return 0;
    }
    int count=accumulate(v.begin(),v.begin()+r+1,0);
    ans = count;
    while (r+2<=v.size()-1) {
        count += v[r+1] - v[l];
        //ans = max({ans,count});
        r++;
        l++;
        count += v[r+1] - v[l];
        ans = max({ans,count});
        r++;
        l++;
    }
    cout << ans << endl;

}

Submission status: Runtime Error

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

longest=0

for bgn_flip in range(len(S)):

    S_copy=S[:]
    zero=False
    icluster=-1
    for i,s in enumerate(S):
        if s==0 and zero==False:
            zero=True
            icluster+=1
        if s==1:
            zero=False

		if s==0 and icluster>=bgn_flip and icluster < bgn_flip+K:
       		S_copy[i]=1

    seq=0
    for sc in S_copy:
        if sc==1:
          seq+=1
        if sc==0:
          seq=0
        if seq>longest:
          longest=seq

print(longest)

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
S = input()
N = len(S)
flag = int(S[0])
S_1 = [len(x) for x in S.split('0') if len(x) is not 0]
S_0 = [len(x) for x in S.split('1') if len(x) is not 0]

count = 0
for i in range(len(S_0)-K+1):
  if flag == 0:
    if i == 0:
      tmp = 0
    else:
      tmp = S_1[i-1]
    for j in range(i,i+K):
      if j == len(S_1):
        tmp += S_0[j]
      else:
        tmp += (S_0[j] + S_1[j])
  else:
    tmp = S_1[i+K]
    for j in range(i,i+K):
      tmp += (S_1[j] + S_0[j])
    
  if tmp > count:
    count = tmp
print(count)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
s=input()
import re
l=[x.span() for x in re.finditer('0+',s)]
from itertools import product
m=0
p=list(product(* ([l]*k)))
for a in p:
  o=s
  if len(set(a))<len(a) and k>1: continue 
  for r in a:
    o=o[0:r[0]]+'1'*(r[1]-r[0])+o[r[1]:]
  f=max([len(x.group())for x in re.finditer('1+',o)])
  if m<f:
    m=f
print(m if m>0 else max([len(x.group())for x in re.finditer('1+',s)]))

Submission status: Runtime Error

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

L = [1]

for i in range(1, N):
	if S[i] == S[i - 1]:
		L[-1] += 1
	else:
		L.append(1)

n = len(L)
if S[0] == "1":
	if n // 2 <= K:
		print(N)
	else:
		if S[-1] == "1":
			x = L[0]
			for i in range(K):
				x += L[2 * i + 1] + L[2 * i + 2]
			val = x
			for i in range(int(n // 2) - K):
				val += L[2 * (i + K) + 1] + L[2 * (i + K) + 2] - L[2 * i] - L[2 * i + 1]
				if val > x:
					x = val
			print(x)
		else:
			x = L[0]
			for i in range(K):
				x += L[2 * i + 1] + L[2 * i + 2]
			val = x
			for i in range(int(n // 2) - K - 1):
				val += L[2 * (i + K) + 1] + L[2 * (i + K) + 2] - L[2 * i] - L[2 * i + 1]
				if val > x:
					x = val
			val += L[-1] - L[-2 * K] - L[-2 * K - 1]
			if val > x:
				x = val
			print(x)			

else:
	if (n + 1) // 2 <= K:
		print(N)
	else:
		if S[-1] == "1":
			LL = [L[-1 - i] for i in range(n)]
			x = LL[0]
			for i in range(K):
				x += LL[2 * i + 1] + LL[2 * i + 2]
			val = x
			for i in range(int(n // 2) - K - 1):
				val += LL[2 * (i + K) + 1] + LL[2 * (i + K) + 2] - LL[2 * i] - LL[2 * i + 1]
				if val > x:
					x = val
			print(x)
		else:
			LL = L[1:]
			x = LL[0]
			for i in range(K):
				x += LL[2 * i + 1] + LL[2 * i + 2]
			val = x
			for i in range(int(n // 2) - K - 1):
				val += LL[2 * (i + K) + 1] + LL[2 * (i + K) + 2] - LL[2 * i] - LL[2 * i + 1]
				if val > x:
					x = val
			val += LL[-1] - LL[-2 * K] - LL[-2 * K - 1]
			if val > x:
				x = val

			LL = [L[-1 - i] for i in range(n - 1)]
			y = LL[0]
			for i in range(K):
				y += LL[2 * i + 1] + LL[2 * i + 2]
			val = y
			for i in range(int(n // 2) - K - 1):
				val += LL[2 * (i + K) + 1] + LL[2 * (i + K) + 2] - LL[2 * i] - LL[2 * i + 1]
				if val > y:
					y = val
			val += LL[-1] - LL[-2 * K] - LL[-2 * K - 1]
			if val > y:
				y = val
			print(max(x, y))

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
S = input()
nowL = 0
if S[0] == '0':
    nowL = 1
L = [0] * N
for i in range(N-1):
    if S[i] == S[i+1]:
        L[nowL] = L[nowL] + 1
    else:
        L[nowL] = L[nowL] + 1
        nowL = nowL + 1
# 終端処理
L[nowL] = L[nowL] + 1

ans = 0
for j in range(N):
    ans = max(ans,sum(L[2*j:2*j+2*K+1]))
    if L[2*j+2*K+1] == 0:
        break

print(ans)

Submission status: Runtime Error

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

S_0 = []
S_1 = []

s_b = S[0]
cnt = 1
for i in range(1,N):
  s_n = S[i]
  if s_n == s_b:
    cnt += 1
  else:
    if s_b == 1:
      S_1.append(cnt)
    else:
      S_0.append(cnt)
    cnt = 1
  s_b = s_n
  
if s_b == 1:
  S_1.append(cnt)
else:
  S_0.append(cnt)

cand = []
if len(S_0) <= K:
  print(len(S))
else:
  if S[0] == 1:
	  for i in range(len(S_1)-K):
  		cand.append(sum(S_0[i:i+K]) + sum(S_1[i:i+K+1]))
  else:
    for i in range(len(S_0)-K):
      cand.append(sum(S_0[i:i+K]) + sum(S_1[i:i+K]))
print(max(cand))

Submission status: Runtime Error

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


if N/2 < K:
    ans = N
else:
    cnt = 0
    state = S[0]
    X = []
    if S[0] == "0":
        X.append(0)
    for i in S:
        if i == state:
            cnt += 1
        else:
            state = i
            X.append(cnt)
            cnt = 1
    X.append(cnt)

    #print(X)
    #print(len(X)-K)

    Y = []
    for i in range(0,len(X)-(K*2+1)+1,2):
        tmp = 0
        for j in range(i,i+(K*2+1)):
            tmp += X[j]
        Y.append(tmp)
    
    #print(Y)

    ans = max(Y)

print(ans)

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
S = list(input())
S = S + ['2']
stlen = []
counter = 0
for i in range(1,len(S)):
    if S[i-1]!=S[i]:
        stlen.append(i-counter)
        counter = i
mmin = 0
if len(S) == 2:
    print('1')  
elif S[0] == '1':
    for i in range(len(stlen)-K-1):
        num = 0
        stlen += [0]
        for j in range(2*K+1):
            num += stlen[i+j]
        if mmin < num:
            mmin = num
    print(mmin)
else:
    for i in range(len(stlen)-K):
        num = 0
        for j in range(2*K):
            num += stlen[i+j]
        if mmin < num:
            mmin = num
    print(mmin)

Submission status: Runtime Error

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

S = input()
a= S[0]
b = int(S[0])
table = []
c = 0
for s in S:
    if int(s) == b:
        c += 1
    else:
        b = not(b)
        table.append(c)
        c = 1

table.append(c)

if a =='0':
    N = 2*K+1
    ans = sum(table[0:2*K])
    for i in range(1,len(table),2):
        if sum(table[i:i+N])>ans:
            ans = (table[i:i+N])
            #ans = max(ans,sum(table[i:i+1+2*K]))

else:
    ans =0
    N = 2*K +1
    for i in range(0,len(table),2):
        if sum(table[i:i+N])>ans:
            ans = sum(table[i:i+N])
        #ans = max(ans,sum(table[i:i+2*K+1]))
#print(table)
print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(100000)
n,k=map(int,input().split())
s=input()
w=[0]*n
def func(k,ans,tmp,q):
    if q>=n:
        return max(ans,tmp)
    if s[q]=='1':
        return func(k,ans,tmp+1,q+1)
    if k==0:
        return max(ans,tmp)
    t=n
    if w[q]>0:
        t=w[q]
    else:
        for i in range(q,n):
            if s[i]=='1':
                t=i
                w[q]=t
                break
    if t==n:
        return max(ans,n-q+tmp)
    a=func(k,max(ans,tmp),0,t)
    b=func(k-1,ans,t-q+tmp,t)
    return max(a,b)
print(func(k,0,0,0))

Submission status: Runtime Error

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

A = [0]
B = [0]
for s in S:
  if s == '1':
    A[-1] += 1
  elif A[-1] != 0:
    A.append(0)
  if s == '0':
    B[-1] += 1
  elif B[-1] != 0:
    B.append(0)

ans = 0

c,d,e,f = 0,0,0,0

for i in range(min(len(A),len(B))):
  a = 0
  if i == 0:
    if S[0] == '1':
      c,d = sum(A[i:min(i + K + 1,len(A))]),sum(B[i:min(i + K,len(B))])
      a = c + d
    else:
      c,d = sum(A[i:min(i + K,len(A))]) , sum(B[i:min(i + K,len(B))])
      a = c + d
  else:
    if S[0] == '1':
      if i + K <= len(A):
        c += A[min(i + K,len(A) - 1)] - A[i - 1]
        d += B[min(i + K - 1,len(A) - 1)] - B[i - 1]
        a = c + d
    else:
      if i + K <= len(A):
        c += A[min(i + K - 1,len(A) - 1)] - (0 if i == 1 else A[i - 2])
        d += B[min(i + K - 1,len(A) - 1)] - B[i - 1]
        a = c + d
  ans = max(ans,a)
print(ans)

Submission status: Runtime Error

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

list0 = list(map(len, S.split("1")))
list1 = list(map(len, S.split("0")))
list0 = [x for x in list0 if x != 0]
list1 = [x for x in list1 if x != 0]

if S[0] == "0":
    list1.insert(0, 0)
else:
    list0.append(0)

ans = 0

for i in range(len(list0)- K + 1):
    num1 = sum(list1[i:i+K])
    num0 = sum(list0[i:i+K])
    ex = 0
    if i+K < len(list0):
        ex = list1[i+K]
    ans = max(ans, num0 + num1 + ex)
    
print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
S = str(input())
L = [0]
for i in range(len(S)-1):
#     print(S[i],S[i+1])
    if S[i] != S[i+1]:
        L.append(i+1)
L.append(len(S))
# print(L)

ans = 1
if N > K * 3:
    for i in range(len(L)-K*2-1):
        ans = max(ans, L[i+K*3-1]-L[i])
    print(ans)
else:
    print(len(S))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
s=input()
import re
l=[x.span() for x in re.finditer('0+',s)]
from itertools import product
m=0
for a in product(* ([l]*k)):
  o=s
  if len(set(a))==1 and k>1: continue 
  for r in a:
    o=o[0:r[0]]+'1'*(r[1]-r[0])+o[r[1]:]
  f=max([len(x.group())for x in re.finditer('1+',o)])
  if m<f:
    m=f
print(m if m>0 else max([len(x.group())for x in re.finditer('1+',s)]))

Submission status: Runtime Error

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

longest=0

for bgn_flip in range(len(S)):

    S_copy=S[:]
    zero=False
    icluster=-1
    for i,s in enumerate(S):
        if s==0 and zero==False:
            zero=True
            icluster+=1
        if s==1:
            zero=False

	if s==0 and icluster>=bgn_flip and icluster < bgn_flip+K:
       	    S_copy[i]=1

    seq=0
    for sc in S_copy:
        if sc==1: seq+=1
        if sc==0: seq=0
        if seq>longest:longest=seq

print(longest)

Submission status: Runtime Error

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

L = [0]
for i in range(len(S)-1):
#     print(S[i],S[i+1])
    if S[i] != S[i+1]:
        L.append(i+1)
L.append(len(S))
# print(L)

ans = 1
if N > K * 3:
    for i in range(len(L)-K*2-1):
        ans = max(ans, L[i+K*3-1]-L[i])
    print(ans)
    print("Yes")
else:
    print(len(S))

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = list(input())
s = [int(x) for x in s]


a = []
b = []
count = 1
pri = s[0]
for i in range(1, n):

    if pri ==1:
        if s[i]==1:
            count += 1
        else:
            a.append(count)
            count = 1
    else:
        if s[i] == 1:
            b.append(count)
            count = 1      
        else:
            count += 1              


    pri = s[i]

if s[n-1] != s[n-2]:
    if s[n-1]==1:
        a.append(1)
    else:
        b.append(1)
elif s[n-1]==1:
    a.append(count)
else:
    b.append(count)


maxx = max(a)
for i in range(len(a)):
    temp = sum(a[i:i+k+1]) + sum(b[i:i+k])
    
    if temp > maxx:
        maxx = temp

print(maxx)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
s=input()
w=[0]*n
def func(k,ans,tmp,q):
    if q>=n:
        return max(ans,tmp)
    if s[q]=='1':
        return func(k,ans,tmp+1,q+1)
    if k==0:
        return max(ans,tmp)
    t=n
    if w[q]>0:
        t=w[q]
    else:
        for i in range(q,n):
            if s[i]=='1':
                t=i
                w[q]=t
                break
    if t==n:
        return max(ans,n-q+tmp)
    a=func(k,max(ans,tmp),0,t)
    b=func(k-1,ans,t-q+tmp,t)
    return max(a,b)
print(func(k,0,0,0))

Submission status: Runtime Error

Solution code:
n,k=list(map(int,input().split()))
t=input()
z=[]
p=t[0]
if t[0]=="0":
  z.append(0)
z.append(0)
for i in t:
  if i == p:
    z[-1]+=1
  eln,k=list(map(int,input().split()))
t=input()
z=[]
p=t[0]
if t[0]=="0":
  z.append(0)
z.append(0)
for i in t:
  if i == p:
    z[-1]+=1
  else:
    p=i
    z.append(1)
if k*2+1 >= len(z):
  r=n
else:
  p=sum(z[:2*k+1])
  r=p
  for i in range(0,len(z)-2*k-2,2):
    e=z[i]+z[i+1]
    p-=e
    f=z[2*k+i+1]+z[2*k+i+2]
    p+=f
    r=max(r,p)
print(r)se:
    p=i
    z.append(1)
if k*2+1 >= len(z):
  r=n
else:
  p=sum(z[:2*k+1])
  r=p
  for i in range(0,len(z)-2*k-2,2):
    e=z[i]+z[i+1]
    p-=e
    f=z[2*k+i+1]+z[2*k+i+2]
    p+=f
    r=max(r,p)
print(r)

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 len(s0) <= K:
        return N
    # error_print(N, K)
    # error_print(S)
    # error_print(s1)
    # error_print(s0)
    ans = 0
    
    
    l1o = 1
    l0o = 0
    l1 = sum(s1[:K+l1o])
    l0 = sum(s0[:K+l0o])
    k = 0
    while True:
        tmp = l1 + l0
        if k == 0 and S[0] == '0':
            tmp -= s1[K]
        ans = max(ans, tmp)
        if k+K < len(s1) and k+K < len(s0):
            l1 -= s1[k]
            if k+K+l1o < len(s1):
                l1 += s1[k+K+l1o]
            l0 -= s0[k]
            if k+K+l0o < len(s0):
                l0 += s0[k+K+l0o]
        else:
            break
        k += 1

    return ans


def main():
    N, K = read_int_n()
    S = read_str()
    rS = ''.join(['0' if c == '1' else '1' for c in S])
    print(max(slv(N, K, S), slv(N, K-1, rS)))

    # 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:
N,K = map(int,input().split(" "))
S = input()

w = S[0]
p = 1
P = []
for i in range(1,len(S)):
    if S[i] == w:
        p += 1
    else:
        w = S[i]
        P.append(p)
        p = 1
if sum(P) != len(S):
    P.append(len(S)-sum(P))
# print(P)
# A = [[P[i+k] for k in range(K)]for i in range(len(P))]
A = []
for i in range(len(P)-(K-1)):
    a = 0
    for k in range(K):
        # print(i,i+k)
        a += P[i+k]
    A.append(a)

print(max(A))

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
S=input()
dist=[]
count=1
for i in range(N-1):
    if S[i+1]!=S[i]:
        dist.append(count)
        count=0
    count+=1
dist.append(count)
if S[0]=="0":
    mem=dist[0]
    dist=dist[1:]
dis=[]#1start is ok
for i in range(0,len(dist)//2,2):
    dis.append(dist[i]+dist[i+1])
if len(dis)<=K:
    ans=sum(dis)
else:
    ans=sum(dis[:K])
    for i in range(len(dis)-K):
        if dis[K+i]>K[i]:
            ans+=dis[K+i]-K[i]
if S[0]=="0" and S[-1]=="0":
    if mem>dist[-1]:
        ans+=mem-dist[-1]
if S[-1]=="1":
    ans+=dist[-1]
print(ans)

Submission status: Runtime Error

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

S = str(input())

L = [0]
for i in range(len(S)-1):
#     print(S[i],S[i+1])
    if S[i] != S[i+1]:
        L.append(i+1)
L.append(len(S))
# print(L)

ans = 1
if N > K:
    for i in range(len(L)-K*2-1):
        ans = max(ans, L[i+K*3-1]-L[i])
    print(ans)
else:
    print(len(S))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-

import sys
from itertools import accumulate

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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

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

L=[]
if S[0]=='0':
    L.append(0)
    cur=start=0
else:
    cur=start=1
cnt=0
for i in range(N):
    if cur==0:
        if S[i]=='0':
            cnt+=1
        else:
            L.append(cnt)
            cnt=1
            cur=1
    else:
        if S[i]=='1':
            cnt+=1
        else:
            L.append(cnt)
            cnt=1
            cur=0
else:
    if cnt!=0:
        if cur==0:
            L.append(cnt)
        else:
            L.append(cnt)
if S[-1]=='0':
    L.append(0)

acc=[0]+list(accumulate(L))
acc+=[0]*10000
mx=0
for i in range(0, len(L), 2):
    mx=max(mx, acc[i+(K*2+1)]-acc[i])

print(mx)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
s=list(input())
s=list(map(int,s))
stack=[]
tmp=1
for i in range(1,len(s)):
  if s[i]!=s[i-1]:
    stack.append(tmp)
    tmp=1
  else:
    tmp+=1
stack.append(tmp)
if s[0]==1:
  if len(s)//2<=k:
    print(len(s))
    exit()
if s[0]==0:
  if (len(s)+1)//2<=k:
    print(len(s))
    exit()
acc=[]
acc2=[]
ans=0
if s[0]==1:
  Acc=stack[0]
  Acc2=0
  acc.append(Acc)
  acc2.append(0)
  for i in range(1,len(stack)-len(stack)%2,2):
    Acc+=stack[i]
    Acc+=stack[i+1]
    acc.append(Acc)
    Acc2+=stack[i-1]
    Acc2+=stack[i]
    acc2.append(Acc2)
  if len(stack)%2==1:
    Acc+=stack[-1]
    acc.append(Acc)
    Acc2+=stack[-2]
    Acc2+=stack[-1]
    acc2.append(Acc2)
  for i in range(len(acc)-k-1):
    ans=max(ans,acc[i+k]-acc2[i])
if s[0]==0:
  Acc=stack[0]
  Acc2=0
  acc.append(0)
  acc.append(Acc)
  acc2.append(0)
  for i in range(1,len(stack)-len(stack)%2,2):
    Acc+=stack[i]
    Acc+=stack[i+1]
    acc.append(Acc)
    Acc2+=stack[i-1]
    Acc2+=stack[i]
    acc2.append(Acc2)
  if len(stack)%2==1:
    Acc+=stack[-1]
    acc.append(Acc)
    Acc2+=stack[-2]
    Acc2+=stack[-1]
    acc2.append(Acc2)
  for i in range(len(acc)-k-1):
    ans=max(ans,acc2[i+k]-acc[i])
print(ans)

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'))))

    error_print(N, K)
    error_print(S)
    error_print(s1)
    error_print(s0)
    ans = 0
    
    
    l1o = 1
    l0o = 0
    l1 = sum(s1[:K+l1o])
    l0 = sum(s0[:K+l0o])
    k = 0
    while True:
        tmp = l1 + l0
        if k == 0 and S[0] == '0':
            tmp -= s1[K]
        ans = max(ans, tmp)
        if k+K < len(s1) and k+K < len(s0):
            l1 -= s1[k]
            if k+K+l1o < len(s1):
                l1 += s1[k+K+l1o]
            l0 -= s0[k]
            if k+K+l0o < len(s0):
                l0 += s0[k+K+l0o]
        else:
            break
        k += 1

    return ans


def main():
    N, K = read_int_n()
    S = read_str()
    rS = ''.join(['0' if c == '1' else '1' for c in S])
    print(max(slv(N, K, S), slv(N, K-1, rS)))

    # 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()