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: Wrong Answer

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

wl = []
wc = 0
prevs = None
for i, _s in enumerate(s):
  if prevs is None:
    wl.append(i)
    prevs = _s
    if _s == '0':
      wc += 1
  elif prevs != _s:
    wl.append(i)
    prevs = _s
    if _s == '0':
      wc += 1
wl.append(n)

if k >= wc:
  print(n)
elif s[0] == '0':
  maxl = wl[2*k] - wl[0]
  for l, r in zip(wl[1:], wl[2*k+2:]):
    if r - l > maxl:
      maxl = r - l
  print(maxl)
else:
  maxl = 0
  for l, r in zip(wl, wl[2*k+1:]):
    if r - l > maxl:
      maxl = r - l
  print(maxl)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
S=input()
start=[0]
end=[]
bef=S[0]
for i in range(1,N):
    if S[i]!=bef:
        if bef=='0':
            start.append(i)
        else:
            end.append(i-1)
        bef=S[i]
if S[-1]=='1':
    end.append(N-1)
ans=0
for i in range(len(end)):
    if i-K<0:
        x=0
    else:
        x=start[i-K]
    ans=max(ans,end[i]-x+1)
if S[-1]=='0' and K!=0:
    if len(start)-K<0:
        x=0
    else:
        x=start[-1*K]
    ans=max(ans,N-x)
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = (int(i) for i in input().split())
s = input()

start = s[0]
arr = []
pre = start
cnt = 0
for x in s:
    if x == pre:
        cnt+=1
        continue
    else:
        pre = x
        arr.append(cnt)
        cnt = 1

arr.append(cnt)

if len(arr) == 1:
    print(arr[0])
    exit()

m = 0
if start == "1":
    now = sum(arr[:2*k+1])
    m = now
    for i in range(1, (len(arr)//2)-k+1):
        now = now - arr[2*i-1] - arr[2*i-2] + sum(arr[2*i+2*k-1:2*i+2*k+1]) 
        m = max(now, m)

else:
    m = sum(arr[:2*k])
    now = sum(arr[1:2*k+2])
    for i in range(1, ((len(arr)+1)//2)-k):
        now = now - arr[2*i] - arr[2*i-1] + sum(arr[2*i+2*k:2*i+2*k+2])
        m = max(now, m)
    
print(m)

Submission status: Wrong Answer

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

now=S[0]
count = 0

for i in range(N):
    if now == S[i]:
        count += 1
    else:
        counts.append(count)
        now = S[i]
        count=1

counts.append(count)

ans = 0

if S[0] == 1:
    ans = sum(counts[0:2*K+1])
    kk = ans
    for i in range(2*K+2, len(counts), 2):
        kk = ans-counts[i-2*K-2]-counts[i-2*K-1] + counts[i]+counts[i-1]
        ans = max(kk,ans)

else:
    counts = [1] + counts
    ans = sum(counts[0:2*K+1])-1
    kk = ans+1
    for i in range(2*K+2, len(counts), 2):
        kk = ans-counts[i-2*K-2]-counts[i-2*K-1] + counts[i]+counts[i-1]
        ans = max(kk,ans)

print(ans)

Submission status: Wrong Answer

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

max_row = 2 * K + 1
row_len = len(row)
if row[0][0] == "0":
	if row[row_len - 1][0] == "0":
		row.insert(0,["1",0])
		row.append(["1",0])
	else:
		row.insert(0,["1",0])
else:
	if row[row_len - 1][0] == "0":
		row.append(["1",0])
j = 0
max_ans = 0
if row_len > max_row: 
	while len(row) - max_row +1 > j:
		temp_sum = 0
		for k in range(max_row):
			temp_sum += row[j + k][1]

		if temp_sum > max_ans:
			max_ans = temp_sum
		j += 2
	print(max_ans)
else:
	print(N)

Submission status: Wrong Answer

Solution code:
import math

list=input().split(" ")
n=int(list[0])
k=int(list[1])
s=input()

list2=[]
renzoku=0

if s[0]=='0':
    list2.append(0)

for x in range(n-1):
    renzoku+=1
    if int(s[x])!=int(s[x+1]):
        list2.append(renzoku)
        renzoku=0

list2.append(renzoku+1)

#print(list2)

kaisu=math.ceil(len(list2)/2)-k
max=0
if kaisu<=0:
    max=len(s)

for y in range(kaisu):
    #print(list2[y*2:y*2+(2*k+1)])
    if y==0:
        gokei=sum(list2[y*2:y*2+(2*k+1)])
    else:
        gokei-=(list2[y*2-2]+list2[y*2-1])
        gokei+=(list2[y*2+k*2-1]+list2[y*2+k*2])
    if gokei>max:
        max=gokei
print(max)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
s = input()
c = [1]

for i in range(1, n):
    if s[i] == s[i - 1]:
        c[-1] += 1
    else:
        c.append(1)

if len(c) < 3:
    print(sum(c))
    exit(0)

cs = c
ans = 0

for i in range(k):
    m = 0

    for j in range(len(cs) - 2):
        s3 = cs[j] + cs[j + 1] + cs[j + 2]

        if s3 > m:
            mj = j
    cs[j : j + 2] = [s3]

    if i == k - 1:
        print(s3 - 1)

Submission status: Wrong Answer

Solution code:
import numpy as np
# import copy


n,k = map(int,input().split())
s = [int(a) for a in input()]

ls = []
start = s[0]
prev = s[0]
cnt = 1
for i in range(1,n):
    if s[i] == prev:
        cnt += 1
    else:
        prev = s[i]
        ls.append(cnt)
        cnt = 1
ls.append(cnt)

ma = 0
if start == 1:
    if len(ls) <= 2*k + 1:
        ma = len(ls)
    else:
        ls = np.array(ls)
        attack_points = len(ls) // 2
        for i in range(attack_points+1-k):
            try:
                su = np.sum(ls[2*i:2*k+1+2*i])
            except IndexError:
                su = np.sum(ls[2*i:2*k+2*i])
            
            if su > ma:
                ma = su
else:
    if len(ls) <= 2*k - 1:
        ma = len(ls)
    else:
        ls = np.array(ls)
        attack_points = len(ls) // 2 + 1
        for i in range(attack_points+1-k):
            if i == 0:
                try:
                    su = np.sum(ls[:2*k])
                except IndexError:
                    su = np.sum(ls[:2*k-1])
                if su > ma:
                    ma = su
            elif i == attack_points - k:
                try:
                    su = np.sum(ls[2*i:2*k+2*i])
                except IndexError:
                    su = np.sum(ls[2*i:2*k-1+2*i])
                if su > ma:
                    ma = su
            else:
                try:
                    su = np.sum(ls[2*i-1:2*k+2*i])
                except IndexError:
                    su = np.sum(ls[2*i-1:2*k-1+2*i])
                if su > ma:
                    ma = su
print(ma)

Submission status: Wrong Answer

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

countList = []

isOne = True
cnt = 0
ans = 0
for i in S:
    if isOne:
        if i == "0":
            countList.append(cnt)
            cnt = 0
            isOne = False
    else:
        if i == "1":
            countList.append(cnt)
            cnt = 0
            isOne = True
    cnt += 1
countList.append(cnt)
if(isOne == False):
    countList.append(0)

for i in range(len(countList)):
    if(i*2+2*K+1<=len(countList)):
        ans = max(ans, sum(countList[i*2:i*2+2*K+1]))
    else:
        break
if(len(countList)==1):
    ans = countList[0]
print(ans)

Submission status: Wrong Answer

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

mans = [];
seq = 0;
now = S[0];
if(now == "0"):
    mans.append(0);

for i in S:
    if(i == now):
        seq += 1;
    else:
        mans.append(seq);
        seq = 1;
        if(now=="1"):
            now="0"
        else:
            now="1"

if(seq!=0):
    mans.append(seq);
    if(now=="1"):
        now="0"
    else:
        now="1"
if(now=="0"):
    mans.append(0);

shakutori = [0]
shakunum = 0;

for i in mans:
    shakunum += i;
    shakutori.append(shakunum);

#print(shakutori);

if(len(shakutori) <= 2*K+1):
    print(shakutori[-1]);
else:
    answer = 0;
    for i in range(1,len(shakutori),2):
        if(len(shakutori) <= i+2*K+1):
            break;
        else:
            if(shakutori[i+2*K]-shakutori[i-1] > answer):
                answer = shakutori[i+2*K]-shakutori[i-1];
    print(answer);

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
S=input()
start=[0]
end=[]
bef=S[0]
for i in range(1,N):
    if S[i]!=bef:
        if bef=='0':
            start.append(i)
        else:
            end.append(i-1)
        bef=S[i]
if S[-1]=='1':
    end.append(N-1)
ans=0
for i in range(len(end)):
    if i-K<0:
        x=0
    else:
        x=start[i-K]
    ans=max(ans,end[i]-x+1)
if S[-1]=='0':
    if len(start)-K<0:
        x=0
    else:
        x=start[-1*K]
    ans=max(ans,N-x)
print(ans)

Submission status: Wrong Answer

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

one_zero_count = []
former = -1

count = 1
for idx, s in enumerate(S):
    s = int(s)
    if former < 0:
        former = s
      
    else:
        if former == s:
            count += 1
        else:
            former = s
            one_zero_count.append(count)
            count = 1
    
    if idx == len(S) - 1:
        one_zero_count.append(count)
        

one_zero_count = np.asarray(one_zero_count)
        
seq_len = K*2 + 1
ans = 0
for idx in range(len(one_zero_count) - seq_len+1):
    
    if idx == 0:
        idx_list = [idx+i for i in range(seq_len-1)]
    elif idx == len(one_zero_count) - seq_len - 1:
         idx_list = [idx+1+i for i in range(seq_len)]
    else:
        idx_list = [idx+i for i in range(seq_len)]
    seq_sum = sum(one_zero_count[idx_list])
    if ans < seq_sum:
        ans = seq_sum

if all([int(s) for s in S]):
    print(len(S))
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
input = sys.stdin.readline


def main():
    n,k = map(int,input().split())
    s = list(input())
    tank = []
    judge = True
    if s[0] == '0':
        judge = False
    cnt = 0
    for i in range(n):
        if judge:
            if s[i] == '0':
                tank.append(cnt)
                judge = False
                cnt = 0
            cnt += 1
        else:
            if s[i] == '1':
                tank.append(cnt)
                judge = True
                cnt = 0
            cnt += 1
        if i == n-1:
            tank.append(cnt)
    #print(tank)
    p = len(tank)
    if s[0] == '0' and (p+1)//2 <= k:
        print(n)
        exit()
    if p//2 <= k and s[0] == '1':
        print(n)
        exit()

    ans = 0
    res = 0
    if s[0] == '0':
        for j in range(2*k):
            res += tank[j]
        ans = res
        for j in range(2*k,p):
            if j == 2*k:
                res -= tank[0]
            elif j%2 == 0:
                res= res - tank[j-2*k] -tank[j-2*k+1]
            res += tank[j]
            ans = max(ans,res)

    else:
        for j in range(2*k+1):
            res += tank[j]
        ans = res
        for j in range(2*k+1,p):
            if j % 2 == 1:
                res = res- tank[j-2*k-1]-tank[j-2*k]
            res += tank[j]
            ans = max(ans,res)
        exit()
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
s = input()
s += "@" # banpei

ans, tmp = 0, 0
i = 0
l = 0 # 連続する bit の先頭
t = 0
d = {}
j = 0
while True:
    bit = s[i]
    if bit == "@":
        break
    if bit == "1":
        tmp = i - l + 1
        ans = max(ans, tmp)
    else:
        if k == 0:
            l = d[j]
            j += 1
            k += 1
        k -= 1
        while s[i+1] == "0":
            i += 1
        d[t] = i+1
        t += 1
    i += 1
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import itertools
import sys
import math
from functools import lru_cache

# 1整数
# n = int(input())

# 空白区切り2変数
from queue import Queue
from operator import mul
from functools import reduce
from queue import Queue
from operator import mul
from functools import reduce
from functools import lru_cache

input = sys.stdin.readline

# N個整数
n, k = list(map(int, input().split()))

s = input() + '2'

# 1整数
# n = int(input())

ret = 0


##この文字の次の0まで示す
def next0(l: int):
    if l >= n:
        return l
    l += 1
    while s[l] != '2' and s[l] != '0':
        l += 1
    return min(l, n)


##この文字の次の1まで示す
def next1(l: int):
    if l >= n:
        return l
    l += 1
    while s[l] != '2' and s[l] != '1':
        l += 1
    return min(l, n)


start = 0
end = 0
ret = 0
# まずendをKこ進める
end = next0(end)
for i in range(k):
    end = next1(end)
    end = next0(end)

ret = end - start
#print(start, end, ret)

while end < n:
    start = next1(next0(start))
    end = next0(next1(end))
    ret = max(ret, end - start)
    print(start, end, ret)
print(ret)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
S = list(input())
left = 0
right = -1
onecnt = 0
zerocnt = 0
zeroflag = False
ans = 0

while right < N-1:
    right += 1
    if S[right] == '0' and not zeroflag:
        zerocnt += 1
        zeroflag = True
    elif S[right] == '1' and zeroflag:
        zeroflag = False
        
    if zerocnt > K and zeroflag:
        tmp = right - left
        if tmp > ans:
            ans = tmp
        while True:
            left += 1
            if S[left] == '0':
                left += 1
                break
        zerocnt -= 1

if right-left+1 > ans:
    ans = right-left+1

print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

NK = input().split(' ')
N = int(NK[0])
K = int(NK[1])
S = input()

prev = '0'
count = 0
nums = []
for i in S:
    if i == prev:
        count += 1
    else:
        nums.append(count)
        count = 1
        prev = i
if count > 0:
    nums.append(count)
# print(nums)

C = min(K * 2 + 1, len(nums))
s1 = 0
for i in range(0, C):
    s1 += nums[i]
sums = [s1]
prev = s1
for i in range(0, len(nums) - C):
    s = prev - nums[i] + nums[i + C]
    sums.append(s)
    prev = s
# print(sums)

print(max(sums))

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
S=input()
L=[]
c=0
for i in range(N):
  if c==0 and S[i]=="1":
    c=1
    s=i
  elif c==1 and S[i]=="0":
    c=0
    t=i-1
    L.append([s,t])
if c==1:
  L.append([s,N-1])
if len(L)<=K-1:
  ans=N
elif len(L)==K:
  if L[0][0]!=0 and L[-1][1]!=N-1:
    ans=max(L[-1][1]+1,N-L[0][0])
  else:
    ans=N
else:
  ans=0
  for i in range(len(L)-K):
    ans=max(ans,L[i+K][1]-L[i][0]+1)
  if L[0][0]!=0:
    ans=max(ans,L[3][1]+1)
  if L[-1][1]!=N-1:
    ans=max(ans,N-L[-4][0])
print(ans)

Submission status: Wrong Answer

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

wl = []
wc = 0
prevs = None
for i, _s in enumerate(s):
  if prevs is None:
    wl.append(i)
    prevs = _s
    if _s == '0':
      wc += 1
  elif prevs != _s:
    wl.append(i)
    prevs = _s
    if _s == '0':
      wc += 1
wl.append(n)

if k >= wc:
  print(n)
elif s[0] == '0':
  maxl = 0
  for l, r in zip(wl, wl[2*k:]):
    if r - l > maxl:
      maxl = r - l
  print(maxl)
else:
  maxl = 0
  for l, r in zip(wl, wl[2*k+1:]):
    if r - l > maxl:
      maxl = r - l
  print(maxl)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
S=input()
start=[0]
end=[]
bef=S[0]
for i in range(1,N):
    if S[i]!=bef:
        if bef=='0':
            start.append(i)
        else:
            end.append(i-1)
        bef=S[i]
if S[-1]=='1':
    end.append(N-1)
ans=0
for i in range(len(end)):
    if i-K<0:
        x=0
    else:
        x=start[i-K]
    ans=max(ans,end[i]-x+1)
print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
s=input()
s='0'+s+'0'
S=[]
E=[]
ans=[]
if s[1]=='0':
  S.append(1)
for i in range(n+1):
  if s[i:i+2]=='01':
    S.append(i+1)
  if s[i:i+2]=='10':
    E.append(i)
if s[n]=='0':
  E.append(n)
if S==[] and E==[]:
  print(n)
else:
  for j in range(len(E)-k):
    ans.append(abs(S[j]-E[j+k]))
  if ans==[]:
    print(E[0])
  else:
    print(max(ans)+1)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
def inpl(): return list(map(int, input().split()))
N, K = inpl()
S = input()

x = S[0]
A = []
B = []
tmp = 0
for s in S:
    if s == x:
        tmp += 1
    else:
        if x == "0":
            A.append(tmp)
        else:
            B.append(tmp)
        x = s
        tmp = 1

if tmp > 0:
    if s == "0":
        A.append(tmp)
    else:
        B.append(tmp)

ans = 0
if S[0] == "1":
    T = sum(A[:K]) + sum(B[:K+1])
    ans = max(ans, T)
    for i in range(len(A) - K):
        T += -A[i] + A[i+K] - B[i]
        if len(B) > i + K + 1:
            T += B[i+K+1]
        ans = max(ans, T)
    print(ans)
else:
    T = sum(A[:K]) + sum(B[:K])
    ans = max(ans, T)
    for i in range(len(A) - K):
        T += -A[i] + A[i+K] - B[i]
        if len(B) > i + K:
            T += B[i+K]
        ans = max(ans, T)
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
input = sys.stdin.readline


def main():
    n,k = map(int,input().split())
    s = list(input())
    tank = []
    judge = True
    if s[0] == '0':
        judge = False
    cnt = 0
    for i in range(n):
        if judge:
            if s[i] == '0':
                tank.append(cnt)
                judge = False
                cnt = 0
            cnt += 1
        else:
            if s[i] == '1':
                tank.append(cnt)
                judge = True
                cnt = 0
            cnt += 1
        if i == n-1:
            tank.append(cnt)
    #print(tank)
    p = len(tank)
    ind = 0
    if s[0] == '0' and (p+1)//2 <= k:
        print(n)
        exit()
    if p//2 <= k and s[0] == '1':
        print(n)
        exit()
    ans = 0
    res = 0
    if s[0] == '0':
        for j in range(2*k):
            res += tank[j]
        ans = res
        for j in range(2*k,p):
            if j == 2*k:
                res -= tank[0]
            elif j%2 == 0:
                res= res - tank[j-2*k] -tank[j-2*k+1]
            res += tank[j]
            ans = max(ans,res)

    else:
        for j in range(2*k+1):
            res += tank[j]
        ans = res
        for j in range(2*k+1,p):
            if j % 2 == 1:
                res = res- tank[j-2*k-1]-tank[j-2*k]
            res += tank[j]
            ans = max(ans,res)

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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
    
    k = 0
    l1o = 1 if S[0] == '1' else 0
    l0o = 1 if S[0] == '0' else 0
    l1 = sum(s1[:K+l1o])
    l0 = sum(s0[:K+l0o])
    while True:
        ans = max(ans, l1 + l0)
        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: Wrong Answer

Solution code:
def main():
    ans = 0
    n, k = map(int, input().split())
    s = input()
    arr = []
    if s[0] == '0':
        arr.append(0)
    cnt = 1
    i = 1
    while i != n:
        if s[i] != s[i - 1]:
            arr.append(cnt)
            cnt = 1
        else:
            cnt += 1
        i += 1
    arr.append(cnt)
    if s[-1] == '0':
        arr.append(cnt)
    ans = 0
    curr = arr[0]
    j = 1
    if len(arr) - 1 <= 2 * k:
        print(n)
        return 0
    for i in range(1, len(arr), 2):
        curr += arr[i] + arr[i + 1]
        if i - j == 2 * k:
            curr -= arr[j] + arr[j - 1]
            j += 2
        ans = max(ans, curr)
    print(ans)
    return 0
main()

Submission status: Wrong Answer

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

if(len(s) == 1):
    print(1)
    exit()

num = [1]
flag = True

ans = 0
tmp = s[0]
if(tmp == "1"): flag = False

for i in s[1:]:
    if(tmp == i): num[-1] += 1
    else:
        num.append(1)
        if(len(num)%2 == 0):
            if(k < len(num)//2):
                if(ans < sum(num[:-1])): ans = sum(num[:-1])
                num = num[1:]
                flag = not flag
        else:
            if(k < len(num)//2 + flag):
                if(ans < sum(num[:-1])): ans = sum(num[:-1])
                num = num[1:]
                flag = not flag
        tmp = i

if(ans < sum(num)): ans = sum(num)

print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
s = input()
renzoku = []
count = 0
flag = 0
for i in range(n):
    if s[i] == "1":
        if flag:
            count += 1
        else:
            renzoku.append(count)
            count = 1
        flag = 1
    else:
        if flag:
            renzoku.append(count)
            count = 1
        else:
            count += 1
        flag = 0
renzoku.append(count)
renzoku_t = [0]
for i in range(len(renzoku)):
    renzoku_t.append(renzoku[i] + renzoku_t[i])
ans = 0
for i in range(len(renzoku) - k - k + 1):
    if i == 0 or i == len(renzoku) - k - k:
        ans = max(ans, renzoku_t[i + k + k] - renzoku_t[i])
    else:
        ans = max(ans, renzoku_t[i + k + k + 1] - renzoku_t[i])
print(ans)

Submission status: Wrong Answer

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

b = []
c = 0
d = 0
for i in a:
	if(i == 1):
		if(d>0):
			b.append(d)
			d = 0
		c = c + 1
	else:
		if(c>0):
			b.append(c)
			c = 0
		d = d + 1

ans = 0
for l in range(0,len(b) - 2*K + 1):
	e = sum(b[l:2*K+2])
	if(ans<e):
		ans = e
print(ans)

Submission status: Wrong Answer

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

if S[0] =='0':
  pre = '0'
  memo = {'0': [1], '1':[0]}
else:
  pre = '1'
  memo = {'0': [], '1':[1]}

for s in S[1:]:
  if s==pre:
    memo[s][-1] +=1
  else:
    pre = s
    memo[s].append(1)

if S[-1] =='0':
  memo['1'].append(0)
else:
  memo['0'].append(0)
    
if len(memo['0'])<=K:
  print(len(S))
  exit()

answer = 0
for i in range(len(memo['0'])-K):
  answer = max(answer, sum(memo['0'][i:i+K] + memo['1'][i:i+K+1]))

print(answer)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-


def main():
  _, N = map(int, input().split())
  stats = list(map(int, input()))
  values = []
  prev = -1

  for s in stats:
    if s == prev:
      values[-1][1] += 1
    else:
      values.append([s, 1])
      prev = s

  window = N * 2 + 1
  length = 0
  max_length = 0

  for i in range(len(values)):
    if i - window >= 0:
      length -= values[i - window][1]

    length += values[i][1]

    if values[i][0] == 1:
      max_length = max(length, max_length)

  print(max_length)


if __name__ == '__main__':
  main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")


def solve(N: int, K: int, S: str):
    S = list(S)
    ii = 0
    while K > 0:
        # 0の位置
        for i in range(ii, N):
            if S[i] == "0":
                break
        l = i
        # 0以降の1の位置
        for i in range(l, N):
            if S[i] == "1":
                break
            else:
                S[i] = "1"
        r = i
        ii = r
        K -= 1
    # print(S)
    ans = 0
    for i in range(N):
        if S[i] == "1":
            ans += 1
        else:
            break
    print(ans)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    S = str(next(tokens))  # type: int
    solve(N, K, S)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

a = [0]
i = 0
p = "1"
for t in s:
  if t == p:
    a[i] += 1
  else:
    p = t
    i += 1
    a += [1]
# print(a)

if len(a) <= 2*k+1:
  print(n)
  # print("over")
  quit()

x = sum(a[:2*k+1])
m = x 
for i in range(2*k+1,len(a)):
  # print(i)
  x = x + a[i] - a[i-(2*k+1)]
  if i%2 == 0:
    m = max(m,x)
print(m)

Submission status: Wrong Answer

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

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from itertools import accumulate
n,k = li()
s = ns()

prev = '0'

zeros = []
ones = []

cur = 0
for si in s:
    if si == prev:
        cur += 1
        
    else:
        if prev == '0':
            zeros.append(cur)
            prev = '1'
        else:
            ones.append(cur)
            prev = '0'
        cur = 1
        
if prev == '0':
    zeros.append(cur)
else:
    ones.append(cur)
    zeros.append(0)

if len(ones) == 0 or len(zeros) == 0:
    ans = n

else:
    ans = 0
    zero_cum = [0] + list(accumulate(zeros))
    one_cum = [0] + list(accumulate(ones))
    
    for i in range(len(zeros)-k+1):
        tmp = (zero_cum[i+k] - zero_cum[i])\
                + (one_cum[min(len(ones), i+k)] - one_cum[max(0, i-1)])
        ans = max(ans, tmp)
        
print(ans)

Submission status: Wrong Answer

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

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

def array_count(arr):
    arr_target = [[]]
    cnt = 1
    for i in range(1,len(arr)):
        if arr[i] == arr[i-1]:
            cnt += 1
        else:
            arr_target.append([arr[i-1],cnt])
            cnt = 1
    arr_target.append([arr[len(arr)-1],cnt])
    del arr_target[0]
    return arr_target

ss = array_count(s)
len_ss = len(ss)

ans = -1
for i in range(len_ss-k*2):
    cnt = 0
    if ss[i][0] == 1:
        for j in range(k*2+1):
            cnt += ss[i+j][1]
    else:
        for j in range(k*2):
            cnt += ss[i+j][1]
    ans = max(ans,cnt)

if ans == -1:
    ans = 1
    
print(ans)

Submission status: Wrong Answer

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

X = [0]
if s[0] == "0":
    X.append(0)
for i in range(N):
    if i == N-1 or s[i] != s[i+1]:
        X.append(i+1)
if len(X) <= K*2+1:
    print(N)
else:
    ma = 0
    for i in range(0, len(X) - K*2 - 1, 2):
        ma = max(X[i+K*2+1]-X[i], ma)
    print(ma)