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.

Solution (Python):

import sys
import copy
import collections
from bisect import bisect_left

def main():
	N, K = map(int, input().split(" "))
	S = input()
		
	S0 = S.split("0")
	S1 = S.split("1")
	
	S0 = [x for x in S0 if x]
	S1 = [x for x in S1 if x]
	
	if K == 0:
		ans = 0
		for val in S0:
			tmp = len(val)
			if tmp > ans:
				ans = tmp
		print(ans)
		sys.exit()
		
	if K >= len(S1):
		print(len(S))
		sys.exit()
	
	fst = []
	snd = []
	guu = False
	kii = False
	if S[0] == "1":
		fst = S0
		snd = S1
		kii = True
	else:
		fst = S1
		snd = S0
		guu = True
	
	ansList = []
	while True:
		if len(fst) != 0:
			ansList.append(fst.pop(0))
		if len(snd) != 0:
			ansList.append(snd.pop(0))
		if len(fst) == 0 and len(snd) == 0:
			break
			
	total = []
	for i, val in enumerate(ansList):
		if i == 0:
			total.append(len(val))
			continue
		total.append(total[i-1] + len(val))
	
	ans = 0
	if kii == True:
		for i, val in enumerate(total):
			tmp = 0
			if i == 0:
				tmp = total[2 * K]
			elif i % 2 == 1:
				tmptmp = i+1+(K-1)*2
				if tmptmp >= len(total):
					tmptmp = len(total)-1
				tmp = total[tmptmp] - total[i-1]
			else:
				tmptmp = i+K*2
				if tmptmp >= len(total):
					tmptmp = len(total)-1
				tmp = total[tmptmp] - total[i-1]
			
			if ans < tmp:
				ans = tmp
	else:
		for i, val in enumerate(total):
			tmp = 0
			if i == 0:
				tmp = total[2 * (K-1) + 1]
			elif i % 2 == 1:
				tmptmp = i + K*2
				if tmptmp >= len(total):
					tmptmp = len(total)-1
				tmp = total[tmptmp] - total[i-1]
			else:
				tmptmp = i+1+(K-1)*2
				if tmptmp >= len(total):
					tmptmp = len(total)-1
				tmp = total[tmptmp] - total[i-1]
			
			if ans < tmp:
				ans = tmp
	
	print(ans)
		
	
if __name__ == "__main__":
	main()

Solution (Python):
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
        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)

Solution (Python):
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)

Solution (Python):
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)
if s[-1]=='0':
	m=2*k
else:
	m=2*k+1
t=4*k+1
_max=0
i=len(a)-1
if i- m<0:
	print(n)
else:
	while i-m>=0:
		tmp=a[i]-a[i-m]
		
		if tmp>_max:
			_max=tmp
		m=t-m
		i-=1
	if a[i]>_max:
		_max=a[i]
	print(_max)

Solution (Python):
import sys
N, K = map(int, input().split())
if N == 1:
    print(1)
    sys.exit()
S = input()
cnt = [0]
flag = False
for c in S:
    if c == '0':
        if flag:
            cnt.append(cnt[-1])
        else:
            flag = True
            cnt.append(cnt[-1] + 1)
    else:
        cnt.append(cnt[-1])
        flag = False
ans = 0
left, right = 0, 0
while right < N:
    while right < N:
        right += 1
        if right < N:
            if S[right - 1] == '1' and S[right] == '0':
                break
        else:
            break
    if cnt[right] - cnt[left] <= K:
        ans = max(ans, right - left)
    else:
        while left < N:
            left += 1
            if S[left - 1] == '0' and S[left] == '1':
                break
        if cnt[right] - cnt[left] <= K:
            ans = max(ans, right - left)
print(ans)

Solution (Python):
import sys
N, K = map(int, input().split())
if N == 1:
    print(1)
    sys.exit()
S = input()
cnt = [0]
flag = False
for c in S:
    if c == '0':
        if flag:
            cnt.append(cnt[-1])
        else:
            flag = True
            cnt.append(cnt[-1] + 1)
    else:
        cnt.append(cnt[-1])
        flag = False
ans = 0
left, right = 0, 0
while right < N:    
    while right < N:
        right += 1
        
        if right < N:
            if S[right - 1] == '1' and S[right] == '0':
                
                break
        else:
            break
    if cnt[right] - cnt[left] <= K:
        ans = max(ans, right - left)
        
        
    else:
        
        while left < N:
            left += 1
            
            if S[left - 1] == '0' and S[left] == '1':
                
                break
        if cnt[right] - cnt[left] <= K:
            ans = max(ans, right - left)
            
            
print(ans)

Solution (Python):
N,K = map(int,input().split())
S = input()
L = [0]
ans = 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)
L.append(i)
if len(L)<=2*K+1:
    ans = N
for i in range(0,len(L)-K*2-1,2):
    ans = max(ans,L[i+K*2+1]-L[i])
print(ans)

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

last = -1
ck = K
pre = ''
for i in range(N):
    c = s[i]
    if c == '0' and pre != '0':
        ck -= 1
        if ck < 0:
            last = i - 1
            break
    pre = c
else:
    last = N-1


if last == N-1:print(len(s))
else:
    
    cameLast = False
    ilr = 0
    g_max = 0
    while True:
        
        g_max = max(g_max,last - ilr + 1)
        if cameLast:break
        pre = ''
        for i in range(ilr,N):
            if s[i] == '1' and pre == '0':
                ilr = i
                break
            else:pre = s[i]
        else:
            ilr = len(s) - 1
        prel = ''
        for j in range(last+1,N):
            if s[j] == '0' and prel == '1':
                last = j - 1
                break
            else:prel = s[j]
        else:
            last = len(s) - 1
            cameLast = True
    print(g_max)

Solution (Python):
N,K = map(int,input().split())
S= input()
i,j = 0,0
onenumber = [0] * (K+1)
zeronumber = [0] * K
test, answer = 0,0
infront = ''

for x in S:
    if x == '0':
        if infront == '1':
            test += onenumber[j]
            answer = max(answer,test)
            if j == K:
                j = -1
            j += 1
            if i == K:
                i = 0
            test -= onenumber[j]
            test -= zeronumber[i]
            onenumber[j],zeronumber[i] = 0, 0
        zeronumber[i] += 1
        infront = '0'
    if x == '1':
        if infront == '0':
            test += zeronumber[i]
            i += 1
        onenumber[j] += 1
        infront = '1'

if S[-1] == '0':
    test += zeronumber[i]
else:
    test += onenumber[j]
answer = max(answer,test)
print(answer)

Solution (Python):
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: 
        if change_flg:
            change()
    else: 
        if not change_flg:
            change()
    cnt += 1

ilands.append(cnt)

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

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

results = [0] * (len(ilands) // 2 - (k - 1))
if len(results) < 1 or len(merged) < section:
    print(n)
    exit()

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

print(max(results))

Solution (Python):
import itertools

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


runlen = [len(list(g)) for k, g in itertools.groupby(S)]


if S[0] == '0':
    runlen = [0] + runlen
if S[-1] == '0':
    runlen = runlen + [0]


k = 2 * K + 1
s = sum(runlen[:k])
sublen = [s]
for i in range(2, N - k, 2):
    s -= sum(runlen[i - 2 : i])
    s += sum(runlen[i - 2 + k : i + k])
    sublen.append(s)

print(max(sublen))

Solution (Python):

N, K = map(int, input().split())
S = input()
Nums = []
now = 1 
cnt = 0 

for i in range(N):
  if S[i] == str(now):
    cnt+=1
  else:
    Nums.append(cnt)
    now = 1 - now
    cnt = 1

if cnt != 0:
  Nums.append(cnt)

if len(Nums) % 2 == 0:
  Nums.append(0)

Add = 2 * K + 1
sum = [0] * (len(Nums) + 1)
for i in range(len(Nums)):
  sum[i + 1] = sum[i] + Nums[i]
ans = 0
for i in range(0, len(Nums), 2):
  left = i
  right = min(i + Add, len(Nums))
  tmp = sum[right] - sum[left]
  ans = max(tmp, ans)

print(ans)

Solution (Python):
N,K = (int(num) for num in input().split())
S = input()
pos_10 = []
chgpos = []
if S[0] == "0":
    chgpos.append((0,0))
cur = "0"
a,b = 0,0
for i in range(N):
    if cur=="0" and S[i]=="1":
        a = i
        cur = "1"
    if cur=="1" and S[i]=="0":
        b = i
        cur = "0"
        chgpos.append((a,b))
if S[-1] == "1":
    chgpos.append((a,N))
if S[-1] == "0":
    chgpos.append((N,N))
    
l = len(chgpos)
if K>l-1:
    print(N)
else:
    ans = 0
    for i in range(l-K):
        if chgpos[i+K][1] - chgpos[i][0] > ans:
            ans = chgpos[i+K][1] - chgpos[i][0]
    print(ans)

Solution (Python):
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])
  ans = sum([Sb[i][1] for i in range(2 * k + 1)])
  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)

Solution (Python):


n,k=map(int,raw_input().split())
s=raw_input()
l=[0]
for i in xrange(n-1):
 if s[i+1]!=s[i]:
  l.append(i+1)
l.append(n)
res=0
for i in xrange(len(l)-1):
 idx=min(i+k*2+int(s[l[i]]=='1'),len(l)-1)
 res=max(res,l[idx]-l[i])
print res

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

cand_index = [0] 
for i in range(n-1):
    if s[i] != s[i+1]:
        cand_index.append(i+1)
cand_index.append(n)

count = []
for i in range(len(cand_index)-1):
    index = min(i+2*k+int(s[cand_index[i]]=="1"), len(cand_index)-1)
    count.append(cand_index[index]-cand_index[i])
        
print(max(count))

Solution (Python):
n, k = map(int, input().split())
s = input()
a = []
if s[0] == '0':
    a.append(0)
l = r = 0
while l < n:
    while r < n and s[l] == s[r]:
        r += 1
    a.append(r-l)
    l = r
if s[-1] == '0':
    a.append(0)
m = len(a)
if m // 2 <= k:
    print(n)
else:
    ans = 0
    asum = [0 for _ in range(m+1)]
    for i in range(m):
        asum[i+1] = asum[i] + a[i]
    for i in range(m+1-2*k):
        if i % 2:
            continue
        ans = max(ans, asum[i+2*k+1] - asum[i])
    print(ans)

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

a = []

before = s[0]
first = int(s[0])
count = 1
for x in s[1:]:
    if x != before:
        a.append(count)
        count = 1
    else:
        count += 1
    before = x
a.append(count)

L = 0
R = k * 2
if first == 1:
    R += 1

if R >= len(a):
    print(n)
    exit()

ans = sum(a[:R])
temp = ans

if first == 0:
    temp -= a[0]
    L += 1
    if R < len(a):
        temp += a[R]
    if R + 1 < len(a):
        temp += a[R + 1]
    R += 2
else:
    temp -= a[0] + a[1]
    L += 2
    if R < len(a):
        temp += a[R]
    if R + 1 < len(a):
        temp += a[R + 1]
    R += 2

if R >= len(a):
    ans = max(ans, temp)
    print(ans)
    exit()

ans = max(ans, temp)

while R <= len(a):
    temp -= a[L] + a[L+1]
    if R + 1 < len(a):
        temp += a[R] + a[R + 1]
    elif R < len(a):
        temp += a[R]
    ans = max(ans, temp)
    L += 2
    R += 2

print(ans)

Solution (Python):
n,k = [int(i) for i in input().split()]

s = input()

il = []

qt = 1
ilz = 0
for i in range(1,len(s)):
    if(s[i-1] == s[i]):
        qt+=1
    else:
        if(s[i-1] == '0'):
            ilz+=1
        il.append([s[i-1],qt])
        qt = 1
        
if(qt>0):
    if(s[len(s)-1] == '0'):
        ilz+=1
    il.append([s[len(s)-1],qt])

if(s.count('1') == n):
    print(n)
elif(k>=ilz):
    print(n)
else:

    l = r = 0
    so = 0
    mso = 0
    for i in range(len(il)):

        if(il[r][0] == '1'):
            so+=il[r][1]
        elif(k>0):
            so+=il[r][1]
            k-=1
        else:
            mso = max(mso,so)
            
            while l<len(il) and il[l][0]!='0':
                so -= il[l][1]
                l+=1
            if(l<len(il)):
                so -= il[l][1]
                l+=1
            
            so+=il[r][1]
            
        r+=1
    mso = max(mso,so)
    print(mso)

Solution (Python):
from itertools import accumulate
N,K = map(int, input().split())
S = list(map(int, input()))

groups = list()
now = 1
cnt = 0

for s in S:
    if s == now:
        cnt += 1
    else:
        groups.append(cnt)
        now ^= 1
        cnt = 1

groups.append(cnt)

if len(groups) % 2 == 0:
    groups.append(0)

cumsum = [0] + list(accumulate(groups))

Add = 2 * K + 1

ans = 0

for i in range(0,len(groups), 2):
    left = i
    right = min(i + Add, len(groups))
    tmp = cumsum[right] - cumsum[left]

    ans = max(tmp,ans)

print(ans)

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

l = [0]

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

l.append(n)

ans = 0
for i in range(len(l)-1):
  index = min(i+2*k + int(s[l[i]]=="1"), len(l)-1)
  ans = max(ans, l[index] - l[i])

print(ans)

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




s="1"+s

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

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

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

  

print(cur-cur_tail)

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




s="1"+s

k_pt = 0
cur_tail = 0
for cur in range(1, len(s)):
  cur_tail+=1

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

  if k_pt <= k:
      cur_tail-=1
  elif  s[cur_tail] == '0' and s[cur_tail+1] == '1':
    k_pt-=1

print(cur-cur_tail)

Solution (Python):

from itertools import accumulate


def main(N, K, S):
    cnts = []
    now = '1'
    cnt = 0
    for n in S:
        if now == n:
            cnt += 1
        else:
            cnts.append(cnt)
            cnt = 1
            now = n
    cnts.append(cnt)

    if now == '0': cnts.append(0)
    
    ans = 0
    Add = 2 * K + 1

    sums = [0] + list(accumulate(cnts))

    for i in range(0,len(cnts),2):
        left = i
        right = min(i + Add, len(cnts))
        tmp = sums[right] - sums[left]

        ans = max(tmp, ans)
    print(ans)

if __name__ == "__main__":
    n, k = list(map(int, input().split()))
    s = input()
    main(n, k, s)

Solution (Python):
_, k = (map(int, input().split()))
n = [int(i) for i in list(input())]
rem = n[0]
s = [1]
for i in range(1, len(n)):
    if n[i] == rem:
        s[-1] += 1
    else:
        s.append(1)
        rem = n[i]

imax = 0
sum_ = 0
r = 0
if n[0] == 0:
    s.insert(0, 0)

for l in range(len(s)):
    sum_ += s[l]
    if l % 2 == 1 and l - r > k * 2:
        r += 2
        sum_ -= s[r-2] + s[r-1]
    if sum_ > imax:
        imax = sum_

print(imax)

Solution (Python):



def main(N, K, S):
    cnts = []
    now = 1
    cnt = 0
    for n in S:
        if now == int(n): 
            cnt += 1
        else:
            cnts.append(cnt)
            cnt = 1
            now = 1 - now
    if cnt != 0: cnts.append(cnt)

    if len(cnts) % 2 == 0: cnts.append(0)
    
    ans = 0
    Add = 2 * K + 1

    sums = [0]
    for c in cnts:
        sums.append(sums[-1] + c)

    for i in range(0,len(cnts),2):
        left = i
        right = min(i + Add, len(cnts))
        tmp = sums[right] - sums[left]

        ans = max(tmp, ans)
    print(ans)

if __name__ == "__main__":
    n, k = list(map(int, input().split()))
    s = input()
    main(n, k, s)

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

ans = 0
for i in range(len(l)-1):
    ind = min(i+2*k + int(s[l[i]]=="1"), len(l) - 1)
    ans = max(ans, l[ind] - l[i])

print(ans)

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

prev = s[0]
cnt = 0
l = []
for c in s:
    if c == prev:
        cnt += 1
    else:
        l.append(cnt)
        prev = c
        cnt = 1
l.append(cnt)

if s[0] == "0":
    l = [0] + l
if s[-1] == "0":
    l.append(0)

cumsum = [0]
for i in l:
    cumsum.append(cumsum[-1]+i)


k = min(len(l), 2*k+1)
ans = max(l[::2])
for i in range(len(l) - k + 1):
    if i % 2 == 1:
        continue
    ans = max(ans, cumsum[i+k]- cumsum[i])
print(ans)

Solution (Python):
N,K=map(int,input().split())
s=input()
l=[]
index=0
pre='1'
for i in range(len(s)):
    if s[i]!=pre:
        l.append(i-index)
        pre=s[i]
        index=i
else:
    l.append(i-index+1 if i!=index else 1)
    if s[-1]=='0':
        l.append(0)
Max=sum(l[:min(2*K+1,len(l))])
cur=Max
for i in range(2*K+1,len(l)):
    cur=cur+l[i]-l[i-2*K-1]-l[i-2*K] if i%2 else cur+l[i]
    if cur > Max:
        Max=cur
print(Max)

Solution (Python):
import sys
N,K=map(int,input().split())
s=input()

x=[]
tmp=0
for i in range(N):
    if s[i]=="1":
        if tmp!=0: x.append([tmp,i-1]) 
        tmp=0
    
    else: tmp+=1
if tmp!=0: x.append([tmp,i]) 

l=len(x)
if l<=K: print(N),sys.exit()

y=[ [0, x[1][1]-x[1][0] ] ]
for i in range(1,l-1):
    y.append([x[i-1][1]+1, x[i+1][1]-x[i+1][0] ])

y.append([x[l-2][1]+1 ,N-1])
ans=0
for i in range(l-K+1):
    ans=max(ans,y[i+K-1][1]-y[i][0]+1 )
print(ans)

Solution (Python):



n,k=map(int,input().split())
s=input()
pre=s[0]
cnt=1
st=[]
if s[0]=='0':
    st.append(0)
for i in range(1,n):
    cur=s[i]
    if cur==pre:
        cnt+=1
    else:
        st.append(cnt)
        cnt=1
    pre=cur
if cnt!=0:
    st.append(cnt)
if s[-1]=='0':
    st.append(0)


ac=[]
pre=0
for i in st:
    pre+=i
    ac.append(pre)

ans=0
if 2*k+1>=len(st):
    ans=n
else:
    ans=ac[2*k]
    for i in range(2,len(st)-2*k,2):
        
        ans=max(ans,ac[i+2*k]-ac[i-1])
print(ans)

Solution (Python):
from itertools import accumulate
N,K = map(int, input().split())
S = list(map(int, input()))

groups = list()
now = 1
cnt = 0

for s in S:
    if s == now:
        cnt += 1
    else:
        groups.append(cnt)
        now ^= 1
        cnt = 1

groups.append(cnt)

if len(groups) % 2 == 0:
    groups.append(0)

cumsum = [0] + list(accumulate(groups))

Add = 2 * K + 1

ans = 0

for i in range(0,len(groups), 2):
    left = i
    right = min(i + Add, len(groups))
    tmp = cumsum[right] - cumsum[left]

    ans = max(tmp,ans)

print(ans)

Solution (Python):
'''
WA
'''
n,k = map(int,input().split()) 
t = list(str(input()))
t = [int(s) for s in t]
last = t[0]
temp_c = 0
s = []
con_c = 0
temp_con_c = 0
corrent_p = 0
sum_t = []
for i in range(n):
    if last == t[i]:
        temp_c += 1
    else:
        last = t[i]
        s.append(temp_c)
        temp_c = 1
s.append(temp_c)
if t[n-1] == 0:
    s.append(0)
l = len(s)
if k*2 <= l:
    sum_t.append(0)
    for i in range(l):
        sum_t.append(sum_t[i]+s[i])
    l = len(sum_t)
    if t[0] == 0:
        for i in range(l-k*2-1):
            if i%2 == 0:
                temp_con_c = sum_t[i+k*2]-sum_t[i]
            else:
                temp_con_c = sum_t[i+k*2+1]-sum_t[i]
            if temp_con_c > con_c:
                con_c = temp_con_c
    else:
        for i in range(l-k*2-1):
            if i%2 ==0:
                temp_con_c = sum_t[i+k*2+1]-sum_t[i]
            else:
                temp_con_c = sum_t[i+k*2]-sum_t[i]
            if temp_con_c > con_c:
                con_c = temp_con_c
else:
    con_c = n

print(con_c)

Solution (Python):

import copy
import numpy as np
import random
import bisect 
import math


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

now,cnt = 1,0
Nums = []
for i in range(N):
    if S[i] == str(now):
        cnt += 1
    else:
        Nums.append(cnt)
        cnt = 1
        now = 1 - now

if cnt!=0:
    Nums.append(cnt)

if len(Nums)%2==0:
    Nums.append(0)


"""
Sums = [0]
tmp = 0
for i in range(len(Nums)):
    tmp += Nums[i]
    Sums.append(tmp)

ans = 0
Add = 2*K+1
for i in range(len(Sums)):
    if i%2==0:
        left = i
        right = min(i+Add,len(Sums)-1)
        tmp = Sums[right]-Sums[left]
        ans = max(tmp,ans)
"""

ans = 0
add = 2*K+1
left = 0
right = min(0+add,len(Nums))
pre = sum(Nums[left:right])
ans = pre
for i in range(len(Nums)-add):
    if i%2==0:
        left = i
        right = min(i+add,len(Nums)-1)
        pre += sum(Nums[right:right+2])-sum(Nums[left:left+2])
        ans = max(pre,ans)

print(ans)

Solution (Python):



import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_matrix(H):
    '''
    H is number of rows
    '''
    return [list(map(int, read().split())) for _ in range(H)]


def read_map(H):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read() for _ in range(H)]


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols

    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])

    return ret


N, K = read_ints()
S = read()[:-1]
sum_0 = [0]



now = '1'
for s_next in S:
    if s_next == '0' and now == '1':
        sum_0.append(sum_0[-1] + 1)
    else:
        sum_0.append(sum_0[-1])
    now = s_next

sum_0_2 = [0]



for s_now, s_next in zip(S[:-1], S[1:]):
    if s_next == '1' and s_now == '0':
        sum_0_2.append(sum_0_2[-1] + 1)
    else:
        sum_0_2.append(sum_0_2[-1])

if S[-1] == '0':
    sum_0_2.append(sum_0_2[-1] + 1)
else:
    sum_0_2.append(sum_0_2[-1])






left = 0
right = 1
ans = 1  





for left in range(N - 1):
    while right < N:
        nextright = right+1
        
        if sum_0[nextright] - sum_0_2[left] > K:
            break
        right += 1
    
    ans = max(ans, right - left)  
    

print(ans)

Solution (Python):

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

ones = []
t = 0
for i in range(N):
    if i == 0:
        t += 1
        pass
    elif (S[i - 1] != S[i]):
        ones.append(t)
        t = 1
    else:
        t += 1
ones.append(t)

if S[0] == '0':
    t = ones
    ones = [0]
    ones.extend(t)

res = 0
if len(ones) >= (2 * K + 1):
    for k in range(2 * K + 1):
        res += ones[k]
else:
    print(sum(ones))
    res = -1

ans = res
if res >= 0:
    for i in range(2 * K + 1, len(ones), 2):
        res += ones[i]
        if i + 1 < len(ones):
            res += ones[i + 1]

        res -= ones[i - 2 * K] + ones[i - 2 * K - 1]
        if ans < res:
            ans = res
    print(ans)

Solution (Python):
import sys

N, K = [int(x) for x in input().split()] 
S = [int(x) for x in list(input())] 
index = [0] 
length = [0] 
zeros = 0 

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

if S[0] == 0: 
    
    for i in range(len(index)): 
        if len(index) % 2 == 0: 
            zeros = int(len(index) / 2)
        else: 
            zeros = int((len(index) + 1) / 2) 
            
    for i in range(len(index)): 
        if S[len(S) - 1] == 0: 
            if i % 2 == 1:
                length.append(index[i + 1] - index[i])
        else: 
            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)): 
                length.append((len(S) - 1) - index[i] + 1)

    for i in range(len(index)): 
        if K >= zeros: 
            print(len(S))
            sys.exit()
        
        elif i + (2 * K) <= (len(index) - 1): 
            if i % 2 == 0: 
                length.append(index[(i + (2 * K) - 1) + 1] - index[i])
            else: 
                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: 
    
    for i in range(len(index)): 
        if len(index) % 2 == 0: 
            zeros = int(len(index) / 2)
        else: 
            zeros = int((len(index) - 1) / 2) 
            
    for i in range(len(index)): 
        if S[len(S) - 1] == 0: 
            if i % 2 == 0:
                length.append(index[i + 1] - index[i])
        else: 
            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)): 
                length.append((len(S) - 1) - index[i] + 1)

    for i in range(len(index)): 
        if K >= zeros: 
            print(len(S))
            sys.exit()
        
        elif i + (2 * K) <= (len(index) - 1): 
            if i % 2 == 0: 
                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: 
                length.append(index[(i + (2 * K) - 1) + 1] - index[i])
        elif (i + (2 * K) == len(index) and i % 2 == 0):
            length.append(len(S) - index[i])

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

Solution (Python):

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

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

    
    
    
    
    

if __name__ == '__main__':
    main()

Solution (Python):
import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_matrix(H):
    '''
    H is number of rows
    '''
    return [list(map(int, read().split())) for _ in range(H)]


def read_map(H):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read() for _ in range(H)]


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols

    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])

    return ret


N, K = read_ints()
S = read()[:-1]



num_cnts = []
now = '1'  
cnt = 0
for s in S:
    if s == now:
        cnt += 1
    if s != now:  
        num_cnts.append(cnt)
        now = s
        cnt = 1
num_cnts.append(cnt)

if S[-1] == '0':
    num_cnts.append(0)

assert len(num_cnts) % 2 == 1, '奇数個じゃない！'


add = min(2*K+1, len(num_cnts))  
ans = 1


left = 0
right = 0
tmp = 0  


for next_left in range(0, len(num_cnts) - add + 1, 2):
    
    next_left = next_left  
    next_right = next_left+add

    
    while (next_left > left):
        tmp -= num_cnts[left]
        left += 1

    
    while (next_right > right):
        tmp += num_cnts[right]
        right += 1

    ans = max(ans, tmp)

print(ans)