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 = input()
n_k_list = n_k.split()
K = int(n_k_list[1])
people = input()
people_list = []
now = people[0]
for i in people[1:]:
    if now[-1] == i:
        now += i
    else:
        people_list.append(now)
        now = i
people_list.append(now)

max_count = 0
change_index = None
while K:
    for index, cell in enumerate(people_list):
        if cell[0] == "0":
            if index == 0 and index == people_list.__len__() - 1:
                this_count = cell.__len__()
            elif index == 0:
                this_count = cell.__len__() + people_list[index + 1].__len__()
            elif index == people_list.__len__() - 1:
                this_count = cell.__len__() + people_list[index - 1].__len__()
            else:
                this_count = cell.__len__() + people_list[index - 1].__len__() + people_list[index + 1].__len__()
            if max_count < this_count:
                max_count = this_count
                change_index = index
    if change_index is not None:
        change_char = ""
        for z in range(people_list[change_index].__len__()):
            change_char += "1"
        if change_index == 0 and change_index == people_list.__len__() - 1:
            new_char = change_char
            people_list[change_index] = new_char
        elif change_index == 0:
            new_char = people_list[change_index + 1] + change_char
            people_list[change_index] = new_char
            del people_list[change_index + 1]
        elif change_index == people_list.__len__() - 1:
            new_char = people_list[change_index - 1] + change_char
            people_list[change_index] = new_char
            del people_list[change_index - 1]
        else:
            new_char = people_list[change_index - 1] + people_list[change_index + 1] + change_char
            people_list[change_index] = new_char
            del people_list[change_index + 1]
            del people_list[change_index - 1]
        change_index = None
        K -= 1
    else:
        break
print(max(people_list, key=len).__len__())

Submission status: Wrong Answer

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

if s.count('1') == len(s):
    print(len(s))
    exit()
ans = 0
l = re.findall('0+', s)
# print(l)
t = list(map(len,l))
# print(t)
a = dict(zip(l,t))
a = sorted(a.items(), reverse=True)
# print(a)
tmp1 = s[s.find(a[0][0]):]
tmp2 = s[:s.find(a[0][0]) + len(a[0][0])]
tmp2 = tmp2[::-1]
t1 = re.findall('0+', tmp1)
t2 = re.findall('0+', tmp2)
# print(tmp2)
# print(t2)
n1 = ''
n2 = ''
for i in range(k):
    if len(t1) != 0:
        for i in range(len(t1[0])):
            n1 = n1 + '1'
        tmp1 = tmp1.replace(t1[0],n1,1)
        t1.pop(0)
        t1 = ''
    if len(t2) != 0:
        for i in range(len(t2[0])):
            n2 = n2 + '1'
        tmp2 = tmp2.replace(t2[0],n2,1)
        t2.pop(0)
        # print(tmp2)
        n2 = ''
tmp1 = s[:s.find(a[0][0])] +  tmp1
tmp2 = tmp2[::-1] + s[s.find(a[0][0])+ len(a[0][0]):]
#print(tmp1,tmp2)
ta = re.findall('1+',tmp1)
tb = re.findall('1+',tmp2)
#print(ta,tb)
tta = map(len,ta)
ttaa = max(tta)

ttb = map(len,tb)
ttbb = max(ttb)
print(max(ttaa,ttbb))

Submission status: Wrong Answer

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

ss = []
tt = []

if s[0] == '0':
  tt += [0]

c = 1
for i in range(1, n):
  if s[i-1:i+1] == '00':
    c += 1
  if s[i-1:i+1] == '10':
    tt += [c]
    c = 1
  if s[i-1:i+1] == '11':
    c += 1
  if s[i-1:i+1] == '01':
    ss += [c]
    c = 1
if s[n-1] == '0':
  ss += [c]
else:
  tt += [c]
  
print(ss)
print(tt)

sr = k
tr = k + 1

sl = len(ss)
tl = len(tt)

mm = 0
for i in range(tl):
  try:
    m = sum(ss[i:i+sr]) + sum(tt[i:i+tr])
    if mm < m:
      mm = m
  except:
    pass
print(mm)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
listS=list(input())
bef=0
index=0
startI=0
counter=0
listH=[]
listSaka=[]
while index < len(listS):
    if index ==0:
        bef=listS[index]
        counter=1
    else:
        if listS[index] == bef:
            counter+=1
        else:
            if bef == "1":
                listH.append(counter)
                listSaka.append(0)
            else:
                listH.append(counter)
                listSaka.append(1)
            counter=1
            bef = listS[index]
    index+=1
if bef == "1":
    listH.append(counter)
    listSaka.append(0)
else:
    listH.append(counter)
    listSaka.append(1)
if not 1 in listSaka:
    print(len(listH))
else:
    listSakaI=[]
    index=0
    while index < len(listSaka):
        if listSaka[index]==1:
            listSakaI.append(index)
        index+=1
    if len(listSaka) < k+1:
        print(len(listH))
    else:
        index=0
        max=0
        while index < len(listSakaI)-k+1:
            if index==0:
                sumA = sum(listH[0:listSakaI[index+k]])
            elif index == len(listSakaI)-k:
                sumA = sum(listH[listSakaI[index-1]+1:len(listH)])
            else:
                sumA = sum(listH[listSakaI[index-1]+1:listSakaI[index+k]])
            if sumA > max:
                max=sumA
            index+=1
        print(max)

Submission status: Wrong Answer

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

#K回範囲を選択して反転、を繰り返し、1の連続数を最大にする
#連続した0を１度しか含まないK+1個の1の連続を探して範囲を出力する……？

change = [0]
for i in range(1,N):
    if S[i] == '1' and S[i-1] != '1':
        change.append(i)
    elif S[i] == '0' and S[i-1] != '0':
        change.append(i)

result = 0
if S[0] == '1':
    for i, point in enumerate(change):
        if i + K*2 + 2 > len(change):
            if i % 2 == 0:
                if result < N - point:
                    result = N - point
            else:
                if result < N - point - 1:
                    result = N - point - 1
            break
        if i % 2 == 0:
            if result < change[i + 1 + K*2] - point:
                result = change[i + 1 + K*2] - point
        else:
            if result < change[i + K*2] - change[i-1]:
                result = change[i + K*2] - change[i-1]
else:
    for i, point in enumerate(change):
        if i + K*2 + 2 > len(change):
            if i % 2 == 0:
                if result < N - point - 1:
                    result = N - point - 1
            else:
                if result < N - point:
                    result = N - point
            break
        if i % 2 == 0:
            if i == 0:
                if result < change[i + K*2] - change[i]:
                    result = change[i + K*2] - change[i]
                continue
            if result < change[i + K*2] - change[i-1]:
                result = change[i + K*2] - change[i-1]
        else:
            if result < change[i + 1 + K*2] - point:
                result = change[i + 1 + K*2] - point
print(result)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
S = input()
X = []
ch = S[0]
cnt = 1
for i in range(1, len(S)):
    if S[i] != ch:
        X.append([ch, cnt])
        cnt = 1
        ch = S[i]
    elif S[i] == ch:
        cnt += 1
X.append([ch, cnt])

st = None
if X[0][0] == '0':
    st = 0
else:
    st = 1
en = st +  2 * (K - 1)
re = K
for v in X:
    if v[0] == '0':
        re -= 1

if '0' not in S:
    print(N)
elif re > 0:
    print(N)
else:
    max_1 = 0
    for i in range(st, en):
        max_1 += X[i][1]
    if st == en:
        max_1 += X[st][1]
    if st - 1 >= 0:
        max_1 += X[st - 1][1]
    if en + 1 < len(X):
        max_1 += X[en + 1][1]
    while True:
        if en + 2 >= len(X):
            break
        tmp = max_1
        if st == 0:
            tmp -= X[0][1]
        else:
            tmp -= X[st][1] + X[st - 1][1]
        if en + 2 == len(X) - 1:
            tmp += X[en + 2][1]
        else:
            tmp += X[en + 2][1] + X[en + 1][1]
        st = st + 2
        en = en + 2
        if tmp > max_1:
            max_1 = tmp
    print(max_1)

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をうめる時！0001010100000
    l = 0
    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(tmpk < K and i+1 == L):
            tmpk+=1
            tmpans+=lis[i]
        elif i+1 < L:#うめきった
            ans = max(ans,tmpans)
            if(l == 0):
                tmpans-=lis[r]
                l=9
            else:
                tmpans-=lis[r]+lis[r+1]
            print(tmpans,i)
            tmpans+=lis[i]+lis[i+1]
            r+=2
        elif i+1 == L:#0が最後
            ans = max(ans,tmpans)
            if(l == 0):
                tmpans-=lis[r]
                l=9
            else:
                tmpans-=lis[r]+lis[r+1]
            tmpans+=lis[i]
        # print(tmpans)
    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(tmpk < K and i+1 == L):
            tmpk+=1
            tmpans+=lis[i]
        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
        elif i+1 == L:#0が最後
            ans = max(ans,tmpans)
            tmpans-=lis[r]+lis[r+1]
            tmpans+=lis[i]
        # print(tmpans)
    print(max(ans,tmpans))
# 14 2
# 11101010110011
# 10 1
# 0000000001

Submission status: Wrong Answer

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

k = {}
cnt = 1
flg = False
for i in range(N):
    if S[i] == '0':
        if cnt not in k.keys() :
            k[cnt] = []
        k[cnt].append(i)
        flg = True
    else:
        if flg == True:
            flg = False
            cnt += 1
if S[-1] == '0':
    k[cnt] = [N-1]
else:
    k[cnt] = [N]

if '0' not in S:
    print(1)
    exit()
if N == 1:
    print(1)
    exit()



ans = 0
for i in range(1,cnt):
    if i + K > len(k.keys()):
        break
    if i == 1:
        ans = k[i+K][0]
    else:
        ans = max(ans , k[i+K][0] - k[i][-1] + 1)
print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
s=list(input())
st=[]
en=[]
if s[0]=="1":
    st.append(0)
for i in range(1,n):
    if s[i-1]=="0" and s[i]=="1":
        st.append(i)
    if s[i-1]=="1" and s[i]=="0":
        en.append(i)
if s[n-1]=="1":
    en.append(n)
ans=0
if len(en)+1<=k:
    print(n)
    exit()
if len(en)<=k and s[0]=="1":
    print(n)
    exit()
if len(en)<=k and s[n-1]=="1":
    print(n)
    exit()
if len(en)-1<=k and s[n-1]=="1" and s[0]=="1":
    print(n)
    exit()
    
if len(en)<=k:
    k=len(en)
for i in range(len(en)-k):
    ans=max(ans,en[i+k]-st[i])
if s[0]=="0":
    ans=max(ans,en[k-1])
if s[n-1]=="0":
    ans=max(ans,n-st[len(st)-k]+1)
print(ans,st,en)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
ANS = 0
ans = 0
S = input()
if sum([int(i) for i in S]) == 0:
    ANS = len(S)
l = 0
r = 1
k = 0
if S[0] == '0':
    k = 1
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:
            if l == 0:
                if S[l] == '0':
                    while True:
                        l += 1
                        if S[l] == '1':
                            break
                else:
                    while True:
                        l += 1
                        if S[l] == '0':
                            l += 1
                            break
            else:
                while True:
                    l += 1
                    if S[l] == '0':
                        l += 1
                        break
            r += 1
        else:
            k += 1
            r += 1
    else:
        r += 1
ANS = ans
ans = 0
S = S[::-1]
l = 0
r = 1
k = 0
if S[0] == '0':
    k = 1
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:
            if l == 0:
                if S[l] == '0':
                    while True:
                        l += 1
                        if S[l] == '1':
                            break
                else:
                    while True:
                        l += 1
                        if S[l] == '0':
                            l += 1
                            break
            else:
                while True:
                    l += 1
                    if S[l] == '0':
                        l += 1
                        break
            r += 1
        else:
            k += 1
            r += 1
    else:
        r += 1
ANS = max(ans,ANS)
print(ANS)

Submission status: Wrong Answer

Solution code:
def main():
    n, k = map(int, input().split())
    s = input()
    if len(s.split('0')) == 2:
        print(n)
    m = count(s)
    sl = [s]
    for i in range(k):
        nl = []
        for a in sl:
            for l in range(n):
                for r in range(l+1, n):
                    t = invert(a, l, r)
                    c = count(t)
                    m = m if m > c else c
                    nl.append(t)
        sl = list(set(nl))
        print(len(nl), len(sl))
    print(m)

def count(s):
    return len(sorted(s.split('0'))[-1])

def invert(s, l, r):
    return s[:l] + ''.join([str(abs(p-1)) for p in map(int, list(s[l:r]))]) + s[r:]

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:

a=[0]*(10**5+8)

N,K=map(int,(input().split()))
S=str(input())
s=len(S)
k=1
a[1]=1
for i in range(s-1):
    if S[i] == S[i+1]:
            a[k]+=1
    else:
            a[k+1]+=1
            k+=1
b=0
d=0
KK=min((10**5)//2+1,K)
if S[0]=="0":

    for j in range((10**5)//2+1-KK):
        c=0
        for p in range(2*KK+1):

            c+=a[p+2*j]
            d=max(d,c)
else:
    for j in range((10**5)//2+1-KK):
        c=0
        for p in range(2*KK+1):
            c+=a[p+2*j+1]
            d=max(d,c)
print(d)

Submission status: Wrong Answer

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

li = []
size = []

now = S[0]
cnt = 1

END = False

for i in range(1,N,1):
  before = now
  now = S[i]
  if now == before:
    cnt += 1
  else:
    li.append(before)
    size.append(cnt)
    cnt = 1

li.append(now)
size.append(cnt)

if 3*K > len(size):
  print(sum(size))
  END = True

max_sum = 0

if END:
  pass
else:
  for i in range(K):
    try:
      now_sum = sum(size[i:i+3*K])
      if max_sum < now_sum:
          max_sum = now_sum
    except:
      pass

  print(max_sum)

Submission status: Wrong Answer

Solution code:
from sys import stdin

class group:
  def __init__(self,types,num):
    self.types = types
    self.num = num

  def add(self, n):
    self.num += n

def get_max(group_list):
  max = 0
  for i in range(len(group_list)):
    if (group_list[i].types == 1):
      if ( max < group_list[i].num ):
        max = group_list[i].num
  return max

def join(group_list):
  max = get_max(group_list)
  max_i = 0
  for i in range(len(group_list)):
    if (group_list[i].types == 0):
        mae = 0
        ato = 0
        if ( 0<i ):
          mae = group_list[i-1].num
        if ( i<(len(group_list)-1) ):
          ato = group_list[i+1].num
        after = mae + group_list[i].num + ato
        if ( max < after ):
          max = after
          max_i = i
  if ( max_i != 0 ):
    group_list[max_i].num = max
    if ( max_i<(len(group_list)-1) ):
      group_list.pop(max_i+1)
    if ( 0<max_i ):
      group_list.pop(max_i-1)
  return group_list, max

# main
n, k = [int(x) for x in stdin.readline().rstrip().split()]
s = stdin.readline().rstrip()

group_list = []
before = -1
for i in range(n):
    if ( before != int(s[i]) ):
        g = group(int(s[i]), 1)
        before = int(s[i])
        group_list.append(g)
    else:
        group_list[-1].add(1)

max = get_max(group_list)
for i in range(k):
  group_list, max = join(group_list)

print(max)

Submission status: Wrong Answer

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

# 0or1がいくつずつ連続しているかをリスト化する
ss = []
num = s[0]
cnt = 1

for i in range(1, len(s)):
  if num == s[i]:
    cnt += 1
  else:
    ss.append(cnt)
    num = s[i]
    cnt = 1
ss.append(cnt)

result = 0
# 0始まりでk=2の場合、[0~3],[1~5],[3~7],[5~9],,,[2*n-1 ~ (n+k)*2-1] ただしn=0のとき0はじまり
# nの最大値は？ len(ss)が
# 7 7//2 - k + 1   k = 3, 13  13//2 - 3 + 1  14  14//2 - 3 
# len(ss)//2 - k + 1 ただし偶数のラストは、[2*n-1 ~ ラスト]
if s[0] == '0':
  if len(ss) % 2 == 1:
    if result < sum(ss[0: (k)*2]):
      result = sum(ss[0: (k)*2])
    
    for i in range(1, len(ss)//2 - k + 1):
      if result < sum(ss[2*i-1: (i+k)*2]):
        result = sum(ss[2*i-1: (i+k)*2])
  else:
    for i in range(len(ss)//2 - k):
      if result < sum(ss[2*i-1: (i+k)*2]):
        result = sum(ss[2*i-1: (i+k)*2])
        
    if result < sum(ss[2* (len(ss)//2-k) -1: ]):
      result = sum(ss[2* (len(ss)//2-k) -1: ])

# 1始まりでk=2の場合、[0~4],[2~6],[4~8],[6~10],,,[2*n ~ (n+k)*2]
# 8 8//2 - k  9 9//2 - k（ただし）   k=3  12 12//2 - k
# len(ss)//2 - k ただし奇数のラストは、[2*n ~ ラスト]
else:
  if len(ss) % 2 == 0:
    for i in range(len(ss) // 2 - k + 1):
      if result < sum(ss[2*i: (i+k)*2+1]):
        result = sum(ss[2*i: (i+k)*2+1])
        
  else:
    for i in range(len(ss) // 2 - k):
      if result < sum(ss[2*i: (i+k)*2+1]):
        result = sum(ss[2*i: (i+k)*2+1])

    if result < sum(ss[2* (len(ss)//2-k): ]):
      result = sum(ss[2* (len(ss)//2-k): ])

print(result)

Submission status: Wrong Answer

Solution code:
import numpy as np

N, K = map(int, input().split(" "))
S = np.array([int(i) for i in input()])
pos1 = np.linspace(0,N-1,N)[S == 1]
lst = []
if len(pos1) == 0:
    print(N)
else:    
    st =[pos1[0]]
    for i in pos1[1:]:
        if st[-1] + 1 == i:
            st.append(i)
        else:
            lst.append(st)
            st = [i]
        if i == pos1[-1]:
            lst.append(st)
    lst = [[0]] + lst + [[N-1]]
    time = len(lst) - K
    if time <= 0:
        print(N)
    else:
        print(int(max([max(lst[i+K]) - min(lst[i])+1 for i in range(time)])))

Submission status: Wrong Answer

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def _I(): return int(sys.stdin.readline())
def _F(): return float(sys.stdin.readline())
def pf(s): return print(s, flush=True)

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

"""
逆立ちを連続で何人
まず1を反転させることはないだろう
どの0を選ぶかという問題になる
仮に0が010101...と10**5/2個あったとすると、K個選ぶのを愚直にやると間に合わない
1が一番つながってるところは使いたいみたいな？
もしくは0が一番つながってるところは使いたい？
dpやるなら、何回操作してて、何番目までやってるか
メモ化再起でやりたいい
memo.get('i箇所目でk回反転したとき最長がL')

ある0の場所を反転させる時、そこから離れたところは反転させる必要がないことに着目
計算を無駄にしないようにメモする？

K回指示する場合
K回以下指示はありえない
"""
positions = []
idx = 0
keep = None
one_keep = None
ones = []
while idx < N:
    if S[idx] == '0':
        if keep == None:
            keep = idx
        if one_keep != None:
            ones.append(idx - one_keep)
            one_keep = None
    else:
        if one_keep == None:
            one_keep = idx
        else:
            pass

        # 1の場合は無視
        if keep != None:
            positions.append([keep, idx])
            keep = None
        else:
            # keepしない場合
            keep = None
    idx += 1
else:
    if keep != None:
        positions.append([keep, keep+1])
#  print(positions)
if len(positions) == 0:
    print(N)
    exit()

#もともと右のほうが長い可能性もあり
if len(ones) == 0:
    # 全部0
    print(N)
    exit()
ans = max(ones)

left = 0
for idx in range(len(positions)):
    left = positions[idx][0]
    if left != 0:
        minus = 1
        while True:
            if left - minus < 0:
                break
            if S[left - minus] == '1':
                minus += 1
            else:
                break
        left -= minus
    # positionから右にk個反転させる
    if idx + K -1 >= len(positions):
        break
    end = positions[idx + K-1][1]
    if end != N:
        a = 0
        while True:
            #  print(end, a)
            if end + a >= N:
                a -= 1
                break
            if S[end + a] == '1':
                a += 1
            else:
                break
        end += a

    ans = max(ans, end - left)
print(ans)

Submission status: Wrong Answer

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

if s.count('0') <= k:
	print(n)
	exit()

# 数列に変換
a = []
c = s[0]
num = 1
for i in range(1,n):
	if c == s[i]:
		num += 1
	else:
		a.append(num)
		num = 1
		c = s[i]
a.append(num)

# k+3の区間の最大値を探す。
l = len(a)

maxsum = 0

if l==1:
	print(a[0])
	exit()

if k==1:
	for i in range(l-1):
		maxsum = max(maxsum, a[i]+a[i+1])
	print(maxsum)
	exit()


maxsum = 0
for i in range(l-(k+1)):
	if a[i] == 1:
		maxsum = max(maxsum, sum(a[i:i+3+(k-1)*2]))
	else:
		maxsum = max(maxsum, sum(a[i:i+3+(k-2)*2]))
print(maxsum)

Submission status: Wrong Answer

Solution code:
import numpy

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

tmp = [int(i) for i in list(input())]
person = numpy.array(tmp,dtype = int)

if person[0] == 0:
    first = 0
else:
    first = 1

length_list = []
length = 1

pre = first

for i in person[1:]:
    if i == pre:
        length += 1
    else:
        pre = i
        length_list.append(length)
        length = 1
length_list.append(length)

length_list_len = len(length_list)

if first == 0:
    zero_num = int(length_list_len/2) + length_list_len%2
else:
    zero_num = int(length_list_len/2)



if k > zero_num:
    print(person.shape[0])
else:
    result = []
    if first == 0:
        result.append(sum(length_list[0:2*k]))
        for i in range(1,zero_num):
            result.append(sum(length_list[2*i+1:2*k+2*i+2]))
    else:
        for i in range(zero_num):
            result.append(sum(length_list[2*i:2*k+2*i+1]))
    print(max(result))

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
S= [i for i in input()]
list_1 = []
max = 0
if S[0] == '0':
	list_1.append(0)
for i in range(N-1):
	if S[i] == '1' and S[i+1] == '0':
		list_1.append(i)
if S[N-1] == '1':
	list_1.append(N-1)
if K>=len(list_1) or '0' not in S:
	print(len(S))
else:
	for i in range(len(list_1)-K):
		if list_1[i+K]-list_1[i]+1 > max:
			max = list_1[i+K]-list_1[i]+1
	print(max)

Submission status: Wrong Answer

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

l = []
ll = []
tmp = 1
p = S[0]

for i in range(1, N + 1):
    if p == S[i]:
        tmp += 1
    else:
        if p == 0:
            ll.append(-1)
        else:
            ll.append(1)
        l.append(tmp)
        p = S[i]
        tmp = 1



i = 0
r = 0
k = 0

while True:
    if ll[r] < 0:
        k += 1
    r += 1
    if k >= K:
        break
    if r >= len(l) - 1:
        print(N)
        exit()

ans = sum(l[i:r + 1])
tmp = ans

while r < len(l) - 1 and i <= r:
    if ll[r + 1] < 0:
        if ll[i] < 0:
            tmp -= l[i]
            i + 1
        else:
            tmp -= l[i]
            tmp -= l[i + 1]
            i += 2
    tmp += l[r + 1]
    r += 1
    ans = max(ans, tmp)

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

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
s=list(input())
st=[]
en=[]
if s[0]=="1":
    st.append(0)
for i in range(1,n):
    if s[i-1]=="0" and s[i]=="1":
        st.append(i)
    if s[i-1]=="1" and s[i]=="0":
        en.append(i)
if s[n-1]=="1":
    en.append(n)
ans=0
if len(en)+1<=k:
    print(n)
    exit()
if len(en)<=k and s[0]=="1":
    print(n)
    exit()
if len(en)<=k and s[n-1]=="1":
    print(n)
    exit()
if len(en)-1<=k and s[n-1]=="1" and s[0]=="1":
    print(n)
    exit()
    
if len(en)<=k:
    k=len(en)
for i in range(len(en)-k):
    ans=max(ans,en[i+k]-st[i]+1)
if s[0]=="0":
    ans=max(ans,en[k-1])
if s[n-1]=="0":
    ans=max(ans,n-st[len(st)-k]+1)
print(ans,st,en)

Submission status: Wrong Answer

Solution code:
import math
import functools
import itertools
import numpy as np
import sys
MAX_INT = int(10e10)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N,K = IL()
s = S()

l = []

if s.count("1")==N:
    print(N)
else:
    cnt = 1
    for i in range(N):
        if s[i] == "1":
            cnt += 1
        else:
            if i != N-1:
                if s[i+1]=="0":
                    l.append([cnt,0])
                else:
                    l.append([cnt,-1])
            else:
                l.append([cnt,-1])
            cnt = 1
    else:
        l.append([cnt,-1])

    tmp = 0
    ccnt = 0
    nn = 0
    ans = 0
    for i in range(tmp,len(l)-1):
        if l[i][1]==-1:
            ccnt += 1
            if ccnt == 1:
                tmp = i
        nn += l[i][0]
        if ccnt == K:
            nn += l[i+1][0] -1
            ans = max(ans,nn)
            nn = 0
            ccnt = 0
    print(ans)

Submission status: Wrong Answer

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

S = input()
a= S[0]
b = int(S[0])
table = [0 for i in range(N)]
c = 0
l = 0
for s in S:
    if int(s) == b:
        c += 1
    else:
        b = not(b)
        table[l]=c
        c = 1
        l+=1

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

else:
    ans =0
    N = 2*K +1
    for i in range(0,l,2):
        ans = max(ans,sum(table[i:i+N]))

print(ans)

Submission status: Wrong Answer

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

if S[0] == "0":
  List = []
  count = 0
  mark = "0"
  for i in range(N):
    if S[i] == mark:
      count += 1
    else:
      List = List + [count]
      count = 1
      if mark == "0":
        mark = "1"
      else:
        mark = "0"
  List = List + [count]
  l = len(List)
  if l <= 2 * K:
    print(N)
  else:
    List = [0] + List
    ans = sum(List[:2 * K + 1])
    List = List + [0, 0, 0]
    p = ans
    for i in range(2, l - 2 * K + 1, 2):
      p = p - List[i - 2] - List[i - 1] + List[i + 2 * K - 1] + List[i + 2 * K]
      if p > ans:
        ans = p
    print(ans)

Submission status: Wrong Answer

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

z_l = []
ans = []
total = 0
count = 0
if int(S[0])==0:
    flag = True
    st =0
else:
    flag = False
    st =1
ct = 0
for i in S:
    t = int(i)
    if t==0:
        if flag:
            pass
        else:
            flag=True
            z_l.append(ct)
            ct=0
        count+=1
    else:
        if flag:
            flag=False
            z_l.append(count)
            count=0
        ct+=1
if count==0:
    z_l.append(ct)
else:
    z_l.append(count)
for i in range(N):
    if 2*K>N:
        tmp = sum(z_l[i:])
    else:
        if st:
            tmp = sum(z_l[i:2*K+1])
        else:
            tmp = sum(z_l[i:2*K])
    ans.append(tmp)
total = max(ans)

print(total)

Submission status: Wrong Answer

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

count = 0

a = S.split('1')
a_0 = list(filter(lambda x:x!='',a))
a_0 = [len(s) for s in a_0]

a = S.split('0')
a_1 = list(filter(lambda x:x!='',a))
a_1 = [len(s) for s in a_1]


if((not a_0) or (not a_1)):
    print(1)
else:
    sum_ = []
    if(S[0]=='1'):
        if(len(a_1)>len(a_0)):
            for i in range(len(a_0)):
                sum_.append(a_1[i]+a_1[i+1]+a_0[i])
            result = [sum(sum_[i:i+K]) for i in range(len(sum_)-K)]
        else:
            for i in range(len(a_0)-1):
                sum_.append(a_1[i]+a_1[i+1]+a_0[i])
            sum_.append(a_1[-1]+a_0[-1])
            result = [sum(sum_[i:i+K]) for i in range(len(sum_)-K-1)]
            result.append(sum_[-1])
    else:
        sum_.append(a_0[0]+a_1[0])
        if(len(a_0)==len(a_1)):
            for i in range(len(a_0)-1):
                sum_.append(a_1[i]+a_1[i+1]+a_0[i])
            result = [sum(sum_[i:i+K]) for i in range(1,len(sum_)-K)]
            result.insert(0,sum_[0])
        else:
            for i in range(len(a_0)-2):
                sum_.append(a_1[i]+a_1[i+1]+a_0[i])
            sum_.append(a_0[-1]+a_1[-1])
            result = [sum(sum_[i:i+K]) for i in range(1,len(sum_)-K-1,1)]
            result.append(sum_[-1])
            result.insert(0,sum_[0])
    print(max(result))