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

L = []
R = []
before = S[0]
cnt_zero = 0
cnt_one = 0
len_l = 0
len_r = 0
for i in range(N):
    if before == '0' and S[i] == '0':
        cnt_zero += 1
    elif before == '0' and S[i] == '1':
        before = '1'
        L.append(cnt_zero)
        len_l += 1
        cnt_zero = 0
        cnt_one += 1
    elif before == '1' and S[i] == '0':
        before = '0'
        R.append(cnt_one)
        len_r += 1
        cnt_zero += 1
        cnt_one = 0
    else:
    	cnt_one += 1
if cnt_zero > 0:
    L.append(cnt_zero)
    len_l += 1

if cnt_one > 0:
	R.append(cnt_one)
	len_r += 1
ans = 0
sum_one = 0
if S[0] == '0':
	sum_one = sum(L[:K]) + sum(R[:K])
else:
	sum_one = sum(L[:K]) + sum(R[:K+1])

ans = sum_one
for i in range(len_l)[1:]:
    if i + K > len_l:
        break
    elif i + K == len_l:
        if i + K > len_r:
            sum_one += (L[K+i-1] - L[i-1] - R[i-1])
            ans = max(ans, sum_one)
            break
        else:
            sum_one += (L[K+i-1] + R[K+i] - L[i-1] - R[i-1])
            ans = max(ans, sum_one)
            break
    if S[0] == '0' and i == 1:
        sum_one += (L[K] + R[K] - L[0])
    else:
        sum_one += (L[K+i-1] + R[K+i] - L[i-1] - R[i-1])
    ans = max(ans, sum_one)
print(ans)

Submission status: Runtime Error

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

L = []
R = []
before = S[0]
cnt_zero = 0
cnt_one = 0
len_l = 0
len_r = 0
for i in range(N):
    if before == '0' and S[i] == '0':
        cnt_zero += 1
    elif before == '0' and S[i] == '1':
        before = '1'
        L.append(cnt_zero)
        len_l += 1
        cnt_zero = 0
        cnt_one += 1
    elif before == '1' and S[i] == '0':
        before = '0'
        R.append(cnt_one)
        len_r += 1
        cnt_zero += 1
        cnt_one = 0
    else:
    	cnt_one += 1
if cnt_zero > 0:
    L.append(cnt_zero)
    len_l += 1

if cnt_one > 0:
	R.append(cnt_one)
	len_r += 1
ans = 0
sum_one = 0
if S[0] == '0':
	sum_one = sum(L[:K]) + sum(R[:K])
else:
	sum_one = sum(L[:K]) + sum(R[:K+1])

ans = sum_one
for i in range(len_l)[1:]:
    if i + K > len_l:
        break
    elif i + K == len_l:
        if i + K > len_r:
            sum_one += (L[K+i-1] - L[i-1] - R[i-1])
            ans = max(ans, sum_one)
            break
    if S[0] == '0' and i == 1:
        sum_one += (L[K] + R[K] - L[0])
    else:
        sum_one += (L[K+i-1] + R[K+i] - L[i-1] - R[i-1])
    ans = max(ans, sum_one)
print(ans)

Submission status: Runtime Error

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

L = []
R = []
before = '1'
cnt_zero = 0
cnt_one = 0
len_l = 0
len_r = 0
for i in range(N):
    if before == '0' and S[i] == '0':
        cnt_zero += 1
    elif before == '0' and S[i] == '1':
        before = '1'
        L.append(cnt_zero)
        len_l += 1
        cnt_zero = 0
    elif before == '1' and S[i] == '0':
        before == '0'
        R.append(cnt_one)
        cnt_zero += 1
        cnt_one = 0
	else:
    	cnt_one += 1
      
if cnt_zero != 0:
    L.append(cnt_zero)
    len_l += 1

if cnt_one != 0:
	R.append(cnt_one)
	len_r = 0
ans = 0
sum_one = 0
if S[0] == '0'
	sum_one = sum(L[:K]) + sum(R[:K])
else:
	sum_one = sum(L[:K]) + sum(R[:K+1])

ans = sum_one

for i in range(len_l)[1:]:
  	if i + K > len_r:
		break
	if S[0] == '0' and i == 1:
		sum_one += (L[K] + R[K] - L[0])
    else:
		sum_one += (L[K+i-1] + R[K+i] - L[i-1] - R[i-1])
	ans = max(ans, sum_one)
print(ans)

Submission status: Runtime Error

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

L = []
R = []
before = '1'
cnt_zero = 0
cnt_one = 0
len_l = 0
len_r = 0
for i in range(N):
    if before == '0' and S[i] == '0':
        cnt_zero += 1
    elif before == '0' and S[i] == '1':
        before = '1'
        L.append(cnt_zero)
        len_l += 1
        cnt_zero = 0
    elif before == '1' and S[i] == '0':
        before == '0'
        R.append(cnt_one)
        cnt_zero += 1
        cnt_one = 0
	else:
    	cnt_one += 1
      
if cnt_zero != 0:
    L.append(cnt_zero)
    len_l += 1

if cnt_one != 0:
	R.append(cnt_one)
	len_r = 0
ans = 0
sum_one = 0
if S[0] == '0'
	sum_one = sum(L[:K]) + sum(R[:K])
else:
	sum_one = sum(L[:K]) + sum(R[:K+1])

ans = sum_one

for i in range(len_l)[1:]:
  	if i + K > len_r:
		break
	if S[0] == '0' and i == 1:
      sum_one += (L[K] + R[K] - L[0])
    else:
      sum_one += (L[K+i-1] + R[K+i] - L[i-1] - R[i-1])
	ans = max(ans, sum_one)
print(ans)

Submission status: Runtime Error

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

L = []
before = ''
cnt = 0
len_l = 0
for i in range(N):
    if before == '0' and S[i] == '0':
        cnt += 1
    elif before == '0' and S[i] == '1':
        before = '1'
        L.append(cnt)
        len_l += 1
        cnt = 0
    elif before == '1' and S[i] == '0':
        before == '0'
        cnt += 1
if cnt != 0:
    L.append(cnt)
    n_l += 1

L.sort(reverse=True)

if len_l > K:
    print(sum(L[:K])
else:
    print(sum(L))

Submission status: Runtime Error

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

L = []
before = ''
cnt = 0
len_l = 0
for i in range(N):
  if before == '0' and S[i] == '0':
  	cnt += 1
  elif before == '0' and S[i] == '1':
  	before = '1'
    L.append(cnt)
    len_l += 1
    cnt = 0
  elif before == '1' and S[i] == '0':
    before == '0'
    cnt += 1
if cnt != 0:
  L.append(cnt)
  len_l += 1

L.sort(reverse=True)

if len_l > K:
  print(sum(L[:K])
else:
  print(sum(L))

Submission status: Runtime Error

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

L = []
before = ''
cnt = 0
len_l = 0
for i in range(N):
  if before == '0' and S[i] == '0'
  	cnt += 1
  elif before == '0' and S[i] == '1'
  	before = '1'
    L.append(cnt)
    len_l += 1
    cnt = 0
  elif before == '1' and S[i] == '0'
    before == '0'
    cnt += 1
if cnt != 0:
  L.append(cnt)
  len_l += 1

L.sort(reverse=True)

if len_l > K:
  print(sum(L[:K])
else:
  print(sum(L))

Submission status: Runtime Error

Solution code:
import numpy as np

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

# 連続する同じ数字をブロックにまとめる
States, Cnts = [S[0]], [1]
index = 0
for i in range(1, N):
	if S[i] == States[index]:
		Cnts[index] += 1
	else:
		States.append(S[i])
		Cnts.append(1)
		index += 1

X = np.cumsum(Cnts)  # X[i]=sum(Cnts[0:i+1])
# print(X)

if S[0] == "0":
	ans = X[min(len(X), 2 * K - 1)]
	for xi in range(2, len(X) - 2 * K + 1, 2):
		ans = max(ans, X[xi + 2 * K - 1] - X[xi - 1])
	print(ans)
else:
	ans = X[min(len(X) - 1, 2 * K)]
	for xi in range(2, len(X) - 2 * K, 2):
		ans = max(ans, X[xi + 2 * K] - X[xi - 1])
	print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np

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

# 連続する同じ数字をブロックにまとめる
States, Cnts = [S[0]], [1]
index = 0
for i in range(1, N):
	if S[i] == States[index]:
		Cnts[index] += 1
	else:
		States.append(S[i])
		Cnts.append(1)
		index += 1

X = np.cumsum(Cnts)  # X[i]=sum(Cnts[0:i+1])
# print(X)

if S[0] == "0":
	ans = X[2 * K - 1]
	for i in range(len(X) - 2 * K + 1):
		ans = max(ans, X[i + 2 * K - 1] - X[i])
	print(ans)
else:
	ans = X[2 * K]
	for i in range(len(X) - 2 * K):
		ans = max(ans, X[i + 2 * K] - X[i])
	print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
s=input()
if s[0]=="0":
  a=[0]
else:a=[]
i=0
c=0
while True:
  c+=1
  if s[i]!=s[i+1]:
    a.append(c)
    c=0
  i+=1
  if i==len(s)-1:
    a.append(len(s)-sum(a))
    break
l=len(a)
if 2*k+1>=l:print(l)
else:
  c=sum(a[:2*k+1])
  ans=sum(a[:2*k+1])
  for i in range(l-2*k-1):
    c-=a[i]-a[i+2*k+1]
    if ans<c:
      ans=c
  print(ans)

Submission status: Runtime Error

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

if s[0] == "0":
    s_num = [0]
else:
    s_num = []
pre = s[0]
num = 0

for i in s:
    if pre == i:
        num += 1
    else:
        s_num.append(num)
        num = 1
        pre = "1" if pre == "0" else "0"
else:
    s_num.append(num)

sums = [s_num[0]]

for i,e in enumerate(s_num[1:]):
    sums.append(sums[i] + e)

ret = 0
sums_len = len(sums)-1
for i in range(len(s_num)//2+1,2):
    ret = max(ret,(sums[min(i+k*2+1,sums_len)] - sums[i]))
 
print(ret)

Submission status: Runtime Error

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

s_num = []
s_first = s[0]
pre = s[0]
num = 0

for i in s:
    if pre == i:
        num += 1
    else:
        s_num.append(num)
        num = 1
        pre = "1" if pre == "0" else "0"
else:
    s_num.append(num)
ret = 0
if s_first == "0":
    ret = max(ret,sum(s_num[0:(2*k)]))
    for i in range(1,len(s_num)//2):
        ret = max(ret,sum(s_num[((i-1)*2+1):(2*(i+k))]))
else:
    ret = max(sum(s_num[0:(2*k+1)]))
    for i in range(1,len(s_num)//2):
        ret = max(ret,(sum(s_num[(i*2):(2*(k+i)+1)])))
 
print(ret)

Submission status: Runtime Error

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

s_num = []
s_first = s[0]
pre = s[0]
num = 0

for i in s:
    if pre == i:
        num += 1
    else:
        s_num.append(num)
        num = 1
        pre = "1" if pre == "0" else "0"
else:
    s_num.append(num)
ret = 0
if s_first == "0":
    ret.append(sum(s_num[0:(2*k)]))
    for i in range(1,len(s_num)//2):
        ret = max(ret,sum(s_num[((i-1)*2+1):(2*(i+k))]))
else:
    ret.append(sum(s_num[0:(2*k+1)]))
    for i in range(1,len(s_num)//2):
        ret = max(ret,(sum(s_num[(i*2):(2*(k+i)+1)])))
 
print(ret)

Submission status: Runtime Error

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

end = []
start = []

if s[0] == "1":
	start.append(0)
	end.append(0)
else:
	#仮想的な1の区間を作る
	start.append(0)
	end.append(0)

for i in range(1, n-1):
	if s[i-1] == "0" and s[i] == "1":
		start.append(i)
	if s[i] == "1" and s[i+1] == "0":
		end.append(i)

if s[-1] == "1":
	start.append(n-1)
	end.append(n-1)
else:
	#仮想的な1の区間を作る
	start.append(n-1)
	end.append(n-1)

ans = 0

"""print(start, end, ans)
print(len(start), len(end), ans)
"""
for j in range(len(start) - k):
	temp = end[j+k] - start[j] + 1 
	if temp > ans:
		ans = temp

if len(start) <= k:
	ans = n

print(ans)

Submission status: Runtime Error

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

end = []
start = []

if s[0] == "1":
	start.append(0)
else:
	#仮想的な1の区間を作る
	start.append(0)
	end.append(0)


for i in range(1, n-1):
	if s[i-1] == "0" and s[i] == "1":
		start.append(i)
	if s[i] == "1" and s[i+1] == "0":
		end.append(i)

if s[-1] == "1":
	end.append(n-1)
else:
	#仮想的な1の区間を作る
	start.append(n-1)
	end.append(n-1)

ans = 0
for j in range(len(start) - k):
	temp = end[j+k] - start[j] + 1 
	if temp > ans:
		ans = temp

if len(start) <= k:
	ans = n

print(ans)

Submission status: Runtime Error

Solution code:
# using main() makes code faster from the point of view of "access to variables in global name-space"
# def main():

""" convenient functions
# for i, a in enumerate(iterable)
# q, mod = divmod(a, b)
# divmod(x, y) returns the tuple (x//y, x%y)
# manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
"""

import sys
sys.setrecursionlimit(10**7)
from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
# accumulate() returns iterator! to get list: list(accumulate())
from math import factorial, ceil, floor
def factorize(n):
    """return the factors of the Arg and count of each factor
    
    Args:
        n (long): number to be resolved into factors
    
    Returns:
        list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
    """
    fct = []  # prime factor
    b, e = 2, 0  # base, exponent
    while b * b <= n:
        while n % b == 0:
            n = n // b
            e = e + 1
        if e > 0:
            fct.append((b, e))
        b, e = b + 1, 0
    if n > 1:
        fct.append((n, 1))
    return fct
def combinations_count(n, r):
    """Return the number of selecting r pieces of items from n kinds of items.
    
    Args:
        n (long): number
        r (long): number
    
    Raises:
        Exception: not defined when n or r is negative
    
    Returns:
        long: number
    """
    # TODO: How should I do when n - r is negative?
    if n < 0 or r < 0:
        raise Exception('combinations_count(n, r) not defined when n or r is negative')
    if n - r < r: r = n - r
    if r < 0: return 0
    if r == 0: return 1
    if r == 1: return n
    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]
    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot
    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])
    return result
def combinations_with_replacement_count(n, r):
    """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
    
    Args:
        n (long): number
        r (long): number
    
    Raises:
        Exception: not defined when n or r is negative
    
    Returns:
        long: number
    """
    if n < 0 or r < 0:
        raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
    elif n == 0:
        return 1
    else:
        return combinations_count(n + r - 1, r)
from bisect import bisect_left, bisect_right
from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
from operator import itemgetter
# ex1: List.sort(key=itemgetter(1))
# ex2: sorted(tuples, key=itemgetter(1,2))
from functools import reduce
def chmin(x, y):
    """change minimum
    if x > y, x = y and return (x, True).
    convenient when solving problems of dp[i]
    
    Args:
        x (long): current minimum value
        y (long): potential minimum value
    
    Returns:
        (x, bool): (x, True) when updated, else (x, False)
    """
    if x > y:
        x = y
        return (x, True)
    else:
        return (x, False)
def chmax(x, y):
    """change maximum
    if x < y, x = y and return (x, True).
    convenient when solving problems of dp[i]
    
    Args:
        x (long): current maximum value
        y (long): potential maximum value
    
    Returns:
        (x, bool): (x, True) when updated, else (x, False)
    """
    if x < y:
        x = y
        return (x, True)
    else:
        return (x, False)

from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
def gcds(numbers):
    return reduce(gcd, numbers)
def lcm(x, y):
    return (x * y) // gcd(x, y)
def lcms(numbers):
    return reduce(lcm, numbers, 1)

# first create factorial_list
# fac_list = mod_factorial_list(n)
INF = 10 ** 18
MOD = 10 ** 9 + 7
modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
def modinv(a, p = MOD):
    # evaluate reciprocal using Fermat's little theorem:
    # a**(p-1) is identical to 1 (mod p) when a and p is coprime
    return modpow(a, p-2, p)
def modinv_list(n, p = MOD):
    if n <= 1:
        return [0,1][:n+1]
    else:
        inv_t = [0,1]
        for i in range(2, n+1):
            inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
        return inv_t
def modfactorial_list(n, p = MOD):
    if n == 0:
        return [1]
    else:
        l = [0] * (n+1)
        tmp = 1
        for i in range(1, n+1):
            tmp = tmp * i % p
            l[i] = tmp
        return l
def modcomb(n, k, fac_list = [], p = MOD):
    # fac_list = modfactorial_list(100)
    # print(modcomb(100, 5, modfactorial_list(100)))
    from math import factorial
    if n < 0 or k < 0 or n < k: return 0
    if n == 0 or k == 0: return 1
    if len(fac_list) <= n:
        a = factorial(n) % p
        b = factorial(k) % p
        c = factorial(n-k) % p
    else:
        a = fac_list[n]
        b = fac_list[k]
        c = fac_list[n-k]
    return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
def modadd(a, b, p = MOD):
    return (a + b) % MOD
def modsub(a, b, p = MOD):
    return (a - b) % p
def modmul(a, b, p = MOD):
    return ((a % p) * (b % p)) % p
def moddiv(a, b, p = MOD):
    return modmul(a, modpow(b, p-2, p))

""" initialize variables and set inputs
# initialize variables
    # to initialize list, use [0] * n
    # to initialize two dimentional array, use [[0] * N for _ in range(N)]
# set inputs
    # open(0).read() is a convenient method:
    # ex) n, m, *x = map(int, open(0).read().split())
    #     min(x[::2]) - max(x[1::2])
    # ex2) *x, = map(int, open(0).read().split())
    #     don't forget to add comma after *x if only one variable is used
# preprocessing
    # transpose = [x for x in zip(*data)]
    # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
    # flat = [flatten for inner in data for flatten in inner]
    # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
# calculate and output
    # output pattern
    # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
"""

# functions used
r = lambda: sys.stdin.readline().strip()
r_int = lambda: int(r())
R = lambda: list(map(int, r().split()))
Rfloat = lambda: list(map(float, r().split()))
Rtuple = lambda: tuple(map(int, r().split()))
Rmap = lambda: map(int, r().split())

""" how to treat input
# single int: int(r())
# single string: r()
# single float: float(r())
# line int: R()
# line string: r().split()
# line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
# lines int: [R() for _ in range(n)]
"""



# ----------------------------------
# main
N, K = R()
S = r()
A = [0] * (N+2)

if not "0" in S or not "1" in S:
    print(len(S))
    exit()

tmp = "1"
j = 0
count = 0
for i in range(N):
    if S[i] != tmp:
        A[j] = count
        tmp = S[i]
        j += 1
        count = 1
    else:
        count += 1
else:
    A[j] = count

len_zero = len(A[1::2])
Acc = list(accumulate(A))

i = 0

ch_num = max(K, len_zero)
while 2*ch_num+2*i <= j+1:
    if i == 0:
        ans = Acc[2*K]
    else:
        ans = max(ans, Acc[2*K+2*i]-Acc[2*i-1])
    i += 1
    
print(ans)

# end of main
# ----------------------------------

"""memo: how to use defaultdict of list
# initialize
Dic = defaultdict(list)
# append / extend
Dic[x].append(y)
# for
for k, v in Dic.items():
"""

# if __name__ == '__main__':
#     main()

Submission status: Runtime Error

Solution code:
# using main() makes code faster from the point of view of "access to variables in global name-space"
# def main():

""" convenient functions
# for i, a in enumerate(iterable)
# q, mod = divmod(a, b)
# divmod(x, y) returns the tuple (x//y, x%y)
# manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
"""

import sys
sys.setrecursionlimit(10**7)
from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
# accumulate() returns iterator! to get list: list(accumulate())
from math import factorial, ceil, floor
def factorize(n):
    """return the factors of the Arg and count of each factor
    
    Args:
        n (long): number to be resolved into factors
    
    Returns:
        list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
    """
    fct = []  # prime factor
    b, e = 2, 0  # base, exponent
    while b * b <= n:
        while n % b == 0:
            n = n // b
            e = e + 1
        if e > 0:
            fct.append((b, e))
        b, e = b + 1, 0
    if n > 1:
        fct.append((n, 1))
    return fct
def combinations_count(n, r):
    """Return the number of selecting r pieces of items from n kinds of items.
    
    Args:
        n (long): number
        r (long): number
    
    Raises:
        Exception: not defined when n or r is negative
    
    Returns:
        long: number
    """
    # TODO: How should I do when n - r is negative?
    if n < 0 or r < 0:
        raise Exception('combinations_count(n, r) not defined when n or r is negative')
    if n - r < r: r = n - r
    if r < 0: return 0
    if r == 0: return 1
    if r == 1: return n
    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]
    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot
    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])
    return result
def combinations_with_replacement_count(n, r):
    """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
    
    Args:
        n (long): number
        r (long): number
    
    Raises:
        Exception: not defined when n or r is negative
    
    Returns:
        long: number
    """
    if n < 0 or r < 0:
        raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
    elif n == 0:
        return 1
    else:
        return combinations_count(n + r - 1, r)
from bisect import bisect_left, bisect_right
from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
from operator import itemgetter
# ex1: List.sort(key=itemgetter(1))
# ex2: sorted(tuples, key=itemgetter(1,2))
from functools import reduce
def chmin(x, y):
    """change minimum
    if x > y, x = y and return (x, True).
    convenient when solving problems of dp[i]
    
    Args:
        x (long): current minimum value
        y (long): potential minimum value
    
    Returns:
        (x, bool): (x, True) when updated, else (x, False)
    """
    if x > y:
        x = y
        return (x, True)
    else:
        return (x, False)
def chmax(x, y):
    """change maximum
    if x < y, x = y and return (x, True).
    convenient when solving problems of dp[i]
    
    Args:
        x (long): current maximum value
        y (long): potential maximum value
    
    Returns:
        (x, bool): (x, True) when updated, else (x, False)
    """
    if x < y:
        x = y
        return (x, True)
    else:
        return (x, False)

from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
def gcds(numbers):
    return reduce(gcd, numbers)
def lcm(x, y):
    return (x * y) // gcd(x, y)
def lcms(numbers):
    return reduce(lcm, numbers, 1)

# first create factorial_list
# fac_list = mod_factorial_list(n)
INF = 10 ** 18
MOD = 10 ** 9 + 7
modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
def modinv(a, p = MOD):
    # evaluate reciprocal using Fermat's little theorem:
    # a**(p-1) is identical to 1 (mod p) when a and p is coprime
    return modpow(a, p-2, p)
def modinv_list(n, p = MOD):
    if n <= 1:
        return [0,1][:n+1]
    else:
        inv_t = [0,1]
        for i in range(2, n+1):
            inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
        return inv_t
def modfactorial_list(n, p = MOD):
    if n == 0:
        return [1]
    else:
        l = [0] * (n+1)
        tmp = 1
        for i in range(1, n+1):
            tmp = tmp * i % p
            l[i] = tmp
        return l
def modcomb(n, k, fac_list = [], p = MOD):
    # fac_list = modfactorial_list(100)
    # print(modcomb(100, 5, modfactorial_list(100)))
    from math import factorial
    if n < 0 or k < 0 or n < k: return 0
    if n == 0 or k == 0: return 1
    if len(fac_list) <= n:
        a = factorial(n) % p
        b = factorial(k) % p
        c = factorial(n-k) % p
    else:
        a = fac_list[n]
        b = fac_list[k]
        c = fac_list[n-k]
    return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
def modadd(a, b, p = MOD):
    return (a + b) % MOD
def modsub(a, b, p = MOD):
    return (a - b) % p
def modmul(a, b, p = MOD):
    return ((a % p) * (b % p)) % p
def moddiv(a, b, p = MOD):
    return modmul(a, modpow(b, p-2, p))

""" initialize variables and set inputs
# initialize variables
    # to initialize list, use [0] * n
    # to initialize two dimentional array, use [[0] * N for _ in range(N)]
# set inputs
    # open(0).read() is a convenient method:
    # ex) n, m, *x = map(int, open(0).read().split())
    #     min(x[::2]) - max(x[1::2])
    # ex2) *x, = map(int, open(0).read().split())
    #     don't forget to add comma after *x if only one variable is used
# preprocessing
    # transpose = [x for x in zip(*data)]
    # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
    # flat = [flatten for inner in data for flatten in inner]
    # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
# calculate and output
    # output pattern
    # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
"""

# functions used
r = lambda: sys.stdin.readline().strip()
r_int = lambda: int(r())
R = lambda: list(map(int, r().split()))
Rfloat = lambda: list(map(float, r().split()))
Rtuple = lambda: tuple(map(int, r().split()))
Rmap = lambda: map(int, r().split())

""" how to treat input
# single int: int(r())
# single string: r()
# single float: float(r())
# line int: R()
# line string: r().split()
# line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
# lines int: [R() for _ in range(n)]
"""


# ----------------------------------
# main
N, K = R()
S = r()
A = [0] * (N+2)

if not "0" in S or not "1" in S:
    print(len(S))
    exit()

tmp = "1"
j = 0
count = 0
for i in range(N):
    if S[i] != tmp:
        A[j] = count
        tmp = S[i]
        j += 1
        count = 1
    else:
        count += 1
else:
    A[j] = count

Acc = list(accumulate(A))

i = 0
while 2*K+2*i <= j:
    if i == 0:
        ans = Acc[2*K]
    else:
        ans = max(ans, Acc[2*K+2*i]-Acc[2*i-1])
    i += 1
print(ans)

# end of main
# ----------------------------------

"""memo: how to use defaultdict of list
# initialize
Dic = defaultdict(list)
# append / extend
Dic[x].append(y)
# for
for k, v in Dic.items():
"""

# if __name__ == '__main__':
#     main()