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()
if s[0] == "0":
    zero = []
    one = []
    c = 1
    now = s[0]
    for i in range(1, n):
        if s[i] == now:
            c += 1
            if i == n - 1:
                if now == "0":
                    zero.append(c)
                else:
                    one.append(c)
        else:
            if now == "0":
                zero.append(c)
                if i == n - 1:
                    one.append(1)
            else:
                one.append(c)
                if i == n - 1:
                    zero.append(1)
            c = 1
            now = s[i]

    pos_zero = len(zero)
    #print(zero, one)
    if pos_zero <= k:
        print(n)
        exit()
    q = sum(zero[:k])
    sum_zero = [q]
    for i in range(pos_zero - k):
        q = q - zero[i] + zero[k + i]
        sum_zero.append(q)
    pos_one = len(one)
    q = sum(one[:k])
    sum_one = [q]
    for i in range(pos_one - k):
        q = q - one[i] + one[k + i]
        sum_one.append(q)
    ans = sum_zero[0] + sum_one[0]
    #print(sum_zero)
    #print(sum_one)
    for i in range(1, pos_zero - k + 1):
        if i - 1 < pos_one and i < len(sum_one):
            ansq = sum_zero[i] + sum_one[i] + one[i - 1]
        elif i < len(sum_one):
            ansq = sum_zero[i] + sum_one[i]
        elif i-1 < pos_one:
            ansq = sum_zero[i] + one[i-1]
        else:
            ansq = sum_zero[i]
        ans = max(ans, ansq)

    print(ans)
else:
    s = "0" + s
    n += 1
    zero = []
    one = []
    c = 1
    now = s[0]
    for i in range(1, n):
        if s[i] == now:
            c += 1
            if i == n - 1:
                if now == "0":
                    zero.append(c)
                else:
                    one.append(c)
        else:
            if now == "0":
                zero.append(c)
                if i == n - 1:
                    one.append(1)
            else:
                one.append(c)
                if i == n - 1:
                    zero.append(1)
            c = 1
            now = s[i]

    pos_zero = len(zero)
    #print(zero, one)
    if pos_zero <= k:
        print(n-1)
        exit()
    q = sum(zero[:k])
    sum_zero = [q]
    for i in range(pos_zero - k):
        q = q - zero[i] + zero[k + i]
        sum_zero.append(q)
    pos_one = len(one)
    q = sum(one[:k])
    sum_one = [q]
    for i in range(pos_one - k):
        q = q - one[i] + one[k + i]
        sum_one.append(q)
    ans = sum_zero[0] + sum_one[0] - 1
    #print(sum_zero)
    #print(sum_one)
    for i in range(1, pos_zero - k + 1):
        if i - 1 < pos_one and i < len(sum_one):
            ansq = sum_zero[i] + sum_one[i] + one[i - 1]
        elif i < len(sum_one):
            ansq = sum_zero[i] + sum_one[i]
        elif i-1 < pos_one:
            ansq = sum_zero[i] + one[i-1]
        else:
            ansq = sum_zero[i]
        ans = max(ans, ansq)

    print(ans)

Submission status: Wrong Answer

Solution code:
def calcH(NormS):
    Kcount = 0
    Hcount = 0
    isFlag = False
    for ns in NormS:
        #0の文字列かつ最大支持
        if ns =='0' and Kcount==K:
            break
        elif ns =='0':
            isFlag = True
        
        #最初の1を除く1が出た時
        elif ns =='1' and isFlag == True:
            isFlag = False
            Kcount += 1
    
        Hcount += 1
    return(Hcount)

N, K = (int(i) for i in input().split())
S = list(input())
lH = calcH(S)
rH = calcH(S[::-1])
print(max(lH,rH))

Submission status: Wrong Answer

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

import numpy as np
line = np.zeros([n,],dtype=np.int)
counter1 = 0
counter0 = 0
ind = 0
for i in range(n):
    c = int(s[i])
    if ind%2 ==0:
        if c == 1:
            counter1 += 1
        else:
            counter0 += 1
            line[ind] = counter1
            counter1 = 0
            ind+=1
    elif ind%2 ==1:
        if c == 0:
            counter0 += 1
        else:
            counter1 += 1
            line[ind] = counter0
            counter0 = 0
            ind+=1

if ind%2 ==0:
        line[ind] = counter1
        ind+=1
elif ind%2 ==1:
        line[ind] = counter0
        ind+=1
line = line[:ind]    
#print(line)

if (len(line)//2)<=k:
    print(n)
else:
    maxchain = 0
    for i in range(0,len(line)-(2*k+1)+1,2):
        chain = sum(line[i:i+2*k+1])
        if chain>maxchain:
            maxchain=chain
    print(maxchain)

Submission status: Wrong Answer

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

max_row = 2 * K + 1

if max_row >= len(row):
	print(N)
else:
	if S[-1] == "0":
		row.append(0)
	if S[0] == "0":
		row.append(0)
	sum_count = []
	temp_sum = 0
	for i in range(max_row):
		temp_sum += row[i]
	sum_count.append(temp_sum)
	i = max_row
	while i < len(row):
		sum_count.append(sum_count[-1] + row[i] + row[i+1] - row[i-max_row] - row[i-max_row+1])
		i += 2
	print(max(sum_count))

Submission status: Wrong Answer

Solution code:
import re, copy
from itertools import combinations, permutations

n, k = input().split(" ")
k = int(k)
input_str = input()
input_list = list(input_str)

pattern_0 = re.compile(r"(0+)")
list_0 = []

list_0 = []
for r in pattern_0.finditer(input_str):
    list_0.append([r.start(), r.group()])

a = list()
max_1_count = 0
for a in combinations(list_0, k):
    new_string_list = copy.copy(input_list)
    for i in a:
        new_string_list[i[0]:i[0] + len(i[1])] = ['1' for j in range(0, len(i[1]))]

    pattern_1 = re.compile(r"(1+)")
    res = pattern_1.findall("".join(new_string_list))
    res_list = [len(s) for s in res]

    m = max(res_list)
    if max_1_count < m:
        max_1_count = m
print(max_1_count)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split(' '))
S=input()
left=[]
right=[]
for i in range(len(S)):
	#len(left)>len(right)のとき1区間が開いていると呼ぶ
	#開いているときにS[i]=='1'なら何もしない
	#開いているときにS[i]=='0'ならrightにi-1を追加
	#閉じているときにS[i]=='1'ならleftにiを追加
	#開いているときにS[i]=='0'なら何もしない
	if len(left)>len(right):
		if S[i]=='0':
			right.append(i-1)
	elif len(left)==len(right):
		if S[i]=='1':
			left.append(i)
#右端の通常処理を行なう
#S[-1]=='0'なら区間はすでに閉じているはずなので何もしない
#S[-1]=='1'なら区間はまだ開いているはずなのでrightにN-1を追加して閉じる
if len(left)>len(right):
	right.append(N-1)

left = [0]*K + left + [N-1]*K
right = [0]*K + right + [N-1]*K

print(left)
print(right)

length = [ right[i+K]-left[i]+1 for i in range(len(left)-K) ]

print(max(length))

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


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

Solution code:
N,K = map(int,input().split())
S = input()
l = 0
r = 1
ans = 0
k = 0
while r < N:
    #print(l,r)
    if S[r] == '1':
        r += 1
        ans = max(ans,r-l)
        continue
    if S[r-1] == '1' and S[r] == '0':
        if k == K:
            while True:
                l += 1
                if S[l] == '0':
                    l += 1
                    #k -= 1
                    break
            r += 1
        else:
            k += 1
            r += 1
    else:
        r += 1

print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
s=input()
l1=[]
l2=[]
c=s.count('1')
for i in s.split('1'):
    if i=='':continue
    l1.append(len(i))
for i in s.split('0'):
    if i=='':continue
    l2.append(len(i))
if len(l1)>len(l2):
    l2.append(0)
elif len(l1)<len(l2):
    l1.append(0)

#print(l1,l2)
if len(l1)<=k:
    c+=sum(l1)
else:
    m=0
    out=0
    for i in range(len(l1)-1):
        m=max(0,m+l1[i]+l1[i+1]-l2[i])
        out=max(m,out)
    c+=out
print(c)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
s=list(map(int,input()))
lis_one=[]
lis_zero=[]
if s[0]!=1:
    lis_one.append(0)
i=0
if n==1:
    print(1)
    exit()
while i<n-1:
    cnt=1
    while s[i]==s[i+1]:
        cnt+=1
        i+=1
        if i==n-1:
            break
    if s[i]==0:
        lis_zero.append(cnt)
    else:
        lis_one.append(cnt)
    i+=1
ans=0
oone=[]
zzero=[]
for i in range(len(lis_one)-k):
    oone.append(sum(lis_one[i:i+k+1]))
    zzero.append(sum(lis_zero[i:i+k]))
for i in range(len(oone)):
    ans=max(ans,oone[i]+zzero[i])
print(ans)

Submission status: Wrong Answer

Solution code:
import itertools

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

before = s[0]
count = 1
lst = []
head = True if before == '1' else False
tail = True if s[-1] == '1' else False

for i in s[1:]:
    if i == before:
        count += 1
    else:
        lst.append(count)
        count = 1
        before = i
lst.append(count)

S = 0

lst1 = lst
if not head:
    S = sum(lst1[:2*k])
    lst1 = lst1[1:]
if not tail:
    S = max(S, sum(lst1[-2*k:]))
    lst1 = lst1[:-1]

lst1.insert(0,0)
accum_lst = list(itertools.accumulate(lst1))

#print('accum_lst :', accum_lst)
N = len(lst1)
if N <= 2*k + 1:
    S = max(S, accum_lst[-1])
else:
    K = 2*k+1
    for i in range(0, N-K):
        S = max(S, accum_lst[i+K] - accum_lst[i])
        #print(i, accum_lst[i+K], accum_lst[i])

print(S)

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
b.append(max(c,d))

ans = 0
e = 0

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

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
listS=list(input())
bef=0
index=0
startI=0
counter=0
listH=[]
while index < len(listS):
    if index ==0:
        if listS[index] == "0":
            startI = index
        bef=listS[index]
        counter=1
    else:
        if listS[index] == bef:
            counter+=1
        else:
            if bef == "1":
                listH.append([counter])
                startI=index
            else:
                listH.append([counter, startI, index-1])
            counter=1
            bef = listS[index]
    index+=1
if bef == "1":
    listH.append([counter])
else:
    listH.append([counter, startI, index-1])
listZero=[]
index=0
while index < len(listH):
    if len(listH[index])==1:
        pass
    else:
        index2=index
        count=0
        sum=0
        while index2 < len(listH):
            if len(listH[index2])==1:
                sum += listH[index2][0]
            else:
                count+=1
                if count < 2:
                    sum += listH[index2][0]
                else:
                    break
            index2+=1
        index3=index-1
        while index3 > -1:
            if len(listH[index3]) == 1:
                sum += listH[index3][0]
            else:
                count += 1
                if count < k+1:
                    sum += listH[index3][0]
                else:
                    break
            index3-=1
        listZero.append([sum, listH[index][1], listH[index][2]])
    index+=1
listZero.sort()
listZero.reverse()
if len(listZero)==0:
    print(listH[0][0])
else:
    print(listZero[0][0])

Submission status: Wrong Answer

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


l=[]
p="1"
q=0
for i in s:
    if i==p:
        q+=1
    else:
        l.append(q)
        q=1
        if p=="1":
            p="0"
        else:
            p="1"
l.append(q)

r=[0]
def ruiseki(a):
    for i in range(len(a)):
        r.append(r[i]+a[i])
ruiseki(l)
ans=0

if len(r)-(2*k+2)+1<=0:
    print(r[-1])
    import sys
    sys.exit()
    
for i in range(len(r)-(2*k+2)+1):
    if (i+2*k+1)%2==1:
        ans=max(ans,r[i+2*k+1]-r[i])

print(ans)

Submission status: Wrong Answer

Solution code:
from sys import exit
N,K = [int(n) for n in input().split()]
# N = int(input())
# a = [int(input()) for _ in range(N)]
S = str(input())
L = len(S)
if(S[0] == "0"):#偶数Indexがブリッジ
    st0 = True
else:
    st0 = False
tmp = S[0]
lis = []
maxlen = 0
for i in range(1,L):
    if(S[i]!=S[i-1]):
        lis.append(len(tmp))
        maxlen = max(maxlen,len(tmp))
        tmp =S[i]
    else:
        tmp+=S[i]
maxlen = max(maxlen,len(tmp))
lis.append(len(tmp))
# print(maxlen)
# print(lis)
# print(maxlen)
# print(st0)
ans = maxlen
# tmpans = maxlen
L = len(lis)
if(st0):#奇数Indexをうめる時！000101010
    r = 0
    tmpans = 0
    tmpk = 0#うめたかず
    for i in range(0,L,2):
        if(tmpk < K and i+1 < L):#うめられるだけうめてない
            tmpk+=1
            tmpans+=lis[i]+lis[i+1]
        elif i+1 < L:#うめきった
            # print(ans,i)
            ans = max(ans,tmpans)
            tmpans-=lis[r]
            tmpans+=lis[i]+lis[i+1]
            r+=2
    print(max(ans,tmpans))
else:#偶数Indexをうめる時！11101010110011
    r = 0
    tmpans = lis[0]
    tmpk = 0#うめたかず
    for i in range(1,L,2):
        if(tmpk < K and i+1 < L):#うめられるだけうめてない
            tmpk+=1
            tmpans+=lis[i]+lis[i+1]
        elif i+1 < L:#うめきった
            ans = max(ans,tmpans)
            # print(tmpans,i)
            tmpans-=lis[r]+lis[r+1]
            tmpans+=lis[i]+lis[i+1]
            r+=2
    print(max(ans,tmpans))
# 14 2
# 11101010110011
# 10 1
# 0000000001

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n,k = na()
s = ns()
ones = []
a = 0
now = '0'

for i in s:
    if i == now:
        a += 1
    else:
        ones.append(a)
        a = 1
        now = i

ones.append(a)

if (len(ones)+1)//2 <= k:
    print(sum(ones))
    exit()

ans = 0
for j in range((len(ones)+1)//2+1-k):
    print(ones[max(0,j*2-1):(j+k)*2])
    ans = max(ans, sum(ones[max(0,j*2-1):(j+k)*2]))
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

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

zero_list = np.array([len(x) for x in s.split("1") if len(x) > 0])
one_list = np.array([len(x) for x in s.split("0") if len(x) > 0])

if k > len(zero_list):
    print(len(s))
else:
    max_num = 0

    if len(zero_list) < len(one_list):
        for i in range(len(zero_list) - k + 1):
            tmp = zero_list[i:i+k].sum() + one_list[i:i+k+1].sum()
            if tmp > max_num:
                max_num = tmp
    else:
        max_num = zero_list[:k].sum() + one_list[:k].sum()
        for i in range(len(one_list) - k):
            tmp = zero_list[i+1:i+k+1].sum() + one_list[i:i+k+1].sum()
            if tmp > max_num:
                max_num = tmp
        tmp = zero_list[-k:].sum() + one_list[-k:].sum()
        if tmp > max_num:
            max_num = tmp

    print(max_num)

Submission status: Wrong Answer

Solution code:
"""
map(int,input().split())

"""
N,K = map(int,input().split())
S = input()
s = []
for i in range(0,len(S)):
    if S[i] == '0':
        s.append(False)
    else:
        s.append(True)

def max0(s):
    ret = [0,0]
    cnt = [0,0]
    for i in range(0,len(s)):
        if not s[i]:
            if cnt[0] == 0:
                cnt[1] = i
            cnt[0] = cnt[0]+1
        else:
            if cnt[0]>ret[0]:
                ret = cnt
            cnt = [0,0]
    return ret[1]

def max1(s):
    ret = 0
    cnt = 0
    for j in range(0,len(s)):
        if s[j]:
            cnt+=1
        else:
            if cnt>ret:
                ret = cnt
            cnt = 0
    if cnt>ret:
        ret = cnt
    return ret

def haba(s,sta):
    start = sta
    while True:
        if start+1 > len(s):
            break
        if s[start]:
            break
        s[start] = True
        start+=1
    #start = sta
    while True:
        sta-=1
        if sta < 0:
            break
        if not s[sta]:
            break
        
    if sta > 0:
        nextLeft = sta
    else:
        nextLeft = -1

    while True:
        start+=1
        if start>len(s)-1:
            break
        if not s[start]:
            break
        
    if start < len(s):
        nextRight = start
    else:
        nextRight = -1
        
    return s,nextLeft,nextRight

next = max0(s)
for k in range(0,K):
    s,l,r = haba(s,next)
    if l == -1 and r == -1:
        break
    elif l == -1:
        next = r
    elif r == -1:
        next = l
    else:
        if max1(haba(s,r)[0]) > max1(haba(s,l)[0]):
            next = r
        else:
            next = l


print(max1(s))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
st = input() + "4"
cnt = 1
before = 3
line = []
ans = 0

for s in st:
    if s == before:
        cnt +=1
    else:
        line.append(cnt)
        cnt = 1
        before = s

if st[0] == "1":
    start = 1
else:
    start = 2
    ans = sum(line[1:2*k+1])

for i in range(start, len(line)-2*k):
    ans = max(ans, sum(line[i:i+2*k+1])) 

if n <= k:
    ans = n

print(ans)

Submission status: Wrong Answer

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

sentous = []
sentou = 0
counts = [0]
count = 0
prev = 0
for s in S:
    count += 1
    if s == prev and count > 0:
        sentou += 1
    elif s != prev and s == '1':
        sentou += 1
    elif s != prev and s == '0':
        sentous.append(sentou + 1)
        sentou = 0
        if K > 0:
            K -= 1
        else:
            counts.append(count - 1)
            count -= sentous.pop(0)
    prev = s

print(max(max(counts), count))

Submission status: Wrong Answer

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

num_list = []
wk = 0
one_flg = SS[0] == "1"
for i,S in enumerate(SS):
    if one_flg:
        if S == "1":
            wk += 1
        else:
            num_list.append(wk)
            wk = 1
            one_flg = not one_flg
    else:
        if S == "0":
            wk += 1
        else:
            num_list.append(wk)
            wk = 1
            one_flg = not one_flg

num_list.append(wk)
# print(num_list)
one_flg = SS[0] == "1"
chk_num = K * 2 + (1 if one_flg else 0)
# print(chk_num)
ans = 0
for i,num in enumerate(num_list[:-chk_num+1]):
    ans = max(ans,sum(num_list[i:i+chk_num]))

print(ans)

Submission status: Wrong Answer

Solution code:
# coding:utf-8

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

    ans = N
    able = False
    if "0" in S:
        while ans >= K :
            for i in range(N-ans+1):
                sub_s = S[i:i+ans]
                # print(sub_s)
                if not "0" in sub_s:
                    able = True
                    break
                else:
                    index = sub_s.index("0")
                    temp = "0"
                    count = 0
                    # print(index)
                    for j in range(index,len(sub_s)):
                        if temp != sub_s[j]:
                            temp = sub_s[j]
                            count += 1
                    if temp == "1":
                        count -= 1
                    # print(count)
                    if count <= K:
                        able = True
                        break
            if able:
                break
            else:
                ans -= 1
    print(ans)

if __name__ == "__main__":
    main()

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)
            isOne = False
    else:
        if i == "1":
            countList.append(cnt)
            isOne = True
    cnt += 1
countList.append(cnt)
if(isOne == False):
    countList.append(cnt)

for i in range(len(countList)):
    if i*2+2*K<len(countList):
        if i*2-1 < 0:
            ans = max(ans, countList[i*2+2*K])
            continue
        ans = max(ans, countList[i*2+2*K]-countList[i*2-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()

if S.count("1") == N or S.count("0") == N:
  print(N)
else:
  ans = 0
  for i in range(N):
    cnt = 0
    change = 0
    if i != 0 and S[i] == "0":
      continue
    for j in range(i, N):
      if j != 0 and S[j] == "0" and S[j - 1] == "1":
        change += 1
      if S[0] == "0" and change < K or S[0] == "1" and change <= K:
        cnt += 1
      else:
        break
    ans = max(ans, cnt)
  print(ans)

Submission status: Wrong Answer

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):
        tmp += zero_array[t+k] - zero_array[t] + one_array[t+k+flag] - 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: Wrong Answer

Solution code:
import re, copy
from itertools import combinations, permutations

n, k = input().split(" ")
k = int(k)
input_str = input()
input_list = list(input_str)

pattern_0 = re.compile(r"(0+)")
list_0 = []

list_0 = []
for r in pattern_0.finditer(input_str):
    list_0.append([r.start(), r.group()])

print(list_0)

a = list()
max_1_count = 0
for a in combinations(list_0, k):
    new_string_list = copy.copy(input_list)
    for i in a:
        new_string_list[i[0]:i[0] + len(i[1])] = ['1' for j in range(0, len(i[1]))]

    pattern_1 = re.compile(r"(1+)")
    res = pattern_1.findall("".join(new_string_list))
    res_list = [len(s) for s in res]

    m = max(res_list)
    if max_1_count < m:
        max_1_count = m
print(max_1_count)

Submission status: Wrong Answer

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


l=[]
p="1"
q=0
for i in s:
    if i==p:
        q+=1
    else:
        l.append(q)
        q=1
        if p=="1":
            p="0"
        else:
            p="1"
l.append(q)

r=[0]
def ruiseki(a):
    for i in range(len(a)):
        r.append(r[i]+a[i])
ruiseki(l)
ans=0

if len(r)-(2*k+2)+1<=0:
    print(r[-1])
    import sys
    sys.exit()
    
for i in range(len(r)-(2*k+2)+1):
    if (i+2*k+1)%2==1:
        ans=max(ans,r[min(len(r)-1,i+2*k+1)]-r[i])

print(ans)

Submission status: Wrong Answer

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


status = S[0]
temp = 0
values = []

for i in range(N):
    if S[i] == status:
        temp += 1
    else:
        if status == '1':
            temp *= -1
        values.append(temp)
        status = S[i]
        temp = 1

if status == '1':
    temp *= -1
values.append(temp)

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

ans = 0

for i in range(len(values)):
    temp = 0
    renzoku = 0

    if values[i] < 0:
        renzoku = (2 * K + 1)
    else:
        renzoku = 2 * K

    if i + renzoku > len(values):
        break

    for x in range(renzoku):
        temp += abs(values[i + x])

    ans = max(ans, temp)

print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
st = input() + "4"
cnt = 1
before = 3
line = []
ans = 0

for s in st:
    if s == before:
        cnt +=1
    else:
        line.append(cnt)
        cnt = 1
        before = s

if st[0] == "1":
    start = 1
else:
    start = 2
    ans = sum(line[1:2*k+1])

for i in range(start, len(line)-2*k):
    ans = max(ans, sum(line[i:i+2*k+1])) 

if n == 1:
    ans = 1

print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
s = input()
next = 0
l = []
ans = 0
if s[0]=='0':
    cnt=1
else:
    cnt = 0
for i in range(1,n):
    if s[i]=='0' and s[i-1]=='1':
        cnt += 1
    if i<n-1 and s[i]=='0' and s[i+1]=='1':
        l.insert(0,i+1)
    if i<n-1 and s[i]=='1' and s[i+1]=='0' and cnt==k:
        ans = max(ans,i+1-next)
        next = l.pop()
        cnt -= 1
    if i==n-1 and s[i]=='1':
        ans = max(ans,i+1-next)
    if i==n-1 and s[i]=='0':
        ans = max(ans,i+1-next)
if ans==0:
    print(n)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def main():
    n, k = [int(i) for i in input().split()]
    s = input() + "3"
    s0 = []
    s1 = []
    cnt = 0
    start = 1
    for i in range(n+1):
        if start == 1 and s[i] != "1":
            s1.append(cnt)
            cnt = 1
            start = 0
        elif start == 0 and s[i] != "0":
            s0.append(cnt)
            cnt = 1
            start = 1
        else:
            cnt += 1

    ans = max(s1)
    for i in range(n):
        ans = max(ans, sum(s1[i:i+k+1]) + sum(s0[i:i+k]))


    print(ans)
    print(s1, s0)

main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
st = input()
num = 0
state = 0
cumsum = []
for s in st:
    if int(s) == state:
        num += 1
    else:
        cumsum.append(num)
        state = [1, 0][state]
        num = 1
cumsum.append(num)
cumsum = [0] + cumsum # odd 
if len(cumsum) % 2:
    cumsum += [0]
l = min(k * 2, len(cumsum) - 1 - (len(cumsum) % 2))

sumsum = sum(cumsum[:l + 1])
max_sum = sumsum
start_idx = 0
end_idx = l + 1
if len(cumsum) - l + 1 > 1:
    for n in range(1, len(cumsum) - l + 1, 2):
        sumsum = (
            sumsum - sum(cumsum[start_idx: start_idx + 2])
            + sum(cumsum[end_idx: end_idx + 2])
        )
        start_idx += n
        end_idx += n
        max_sum = max(max_sum, sumsum)

print(max_sum)

Submission status: Wrong Answer

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

num = [0]
which = s[0]
sign = [which]
for i in s:
  if i != which:
    which = 1-which
    num.append(0)
    sign.append(which)
  num[-1] += 1

if k >= len(sign) - sum(sign):
  print(sum(num))
  exit()

#print(num)
#print(sign)

if sign[0] == 0:
  num = [0] + num

if sign[-1] == 0:
  num.append(0)

sum_now = sum(num[0:2*k+1])
ans = sum_now

for i in range(0,len(num),2):
  if i == 0:
    continue
  if i+2*k >= len(num):
    break
  
  plus = num[i+2*k-1]+num[i+2*k]
  minus = num[i-2] + num[i-1]
  diff = plus - minus
  sum_now += diff
  if diff > 0:
    ans = sum_now
    
print(ans)