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: Time Limit Exceeded

Solution code:
import re

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

def popcnt(n):
  return bin(n).count("1")

cands = []
for xor in range(2 ** len(S)):
  if len(re.split('1+', bin(xor))) != 2:
    continue
  cands.append(xor)

for _ in range(K):
  best_score = max([len(v) for v in re.findall(r'1+', S)])
  best_xor = 0
  for xor in cands:
    res = intS ^ xor
    try:
      score = max([len(v) for v in re.findall(r'1+', bin(res))])
    except:
      score = 0
    
    if score > best_score:
      best_score = score
      best_xor = xor
      # print(xor, bin(xor), res, bin(res), _popcnt)
        
  intS = intS ^ best_xor
    
print(max([len(v) for v in re.findall(r'1+', bin(intS))]))

Submission status: Time Limit Exceeded

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

# 奇数番目は1のカタマリの人数　偶数番目は0のカタマリの人数 両端は必ず1のカタマリの人数
now_state, now_count = '1', 0
L = []
Ladd = L.append
for i in range(len(S)):
  if S[i] == now_state:
    now_count += 1
  else:
    Ladd(now_count)
    # reset
    now_count = 1
    now_state = '1' if now_state == '0' else '0'
Ladd(now_count)
if now_state == '0':
  Ladd(0)

#print(L)
# 0の塊をj個ひっくり返す
# j==1のとき101の3個の和の最大
# j==2のとき10101の5個の和の最大
# j==jのとき101...1のj*2+1個の和の最大

def evenngram(n, _list):
  return [_list[i:i+n] for i in range(len(_list)-n+1) if i%2==0]

j = min(int((len(L)-1)/2), K) # 0のカタマリをひっくり返せるだけひっくり返す
tmp = evenngram(j*2+1, L)
tmp = max([sum(t) for t in tmp])
print(tmp)

Submission status: Time Limit Exceeded

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

center = []
side = [0]

last = '1'
for s in S:
    if s != last:
        if s == '0':
            center.append(0)
        else:
            side.append(0)
    if s == '0':
        center[-1] += 1
    else:
        side[-1] += 1
    last = s
if last == '0':
    side.append(0)

combined = [sum(center[i:i+K]) + sum(side[i:i+K+1])
            for i in range(len(center) - K + 1)]

if combined:
    print(max(combined))
else:
    print(N)

Submission status: Time Limit Exceeded

Solution code:
N,K = [int(x) for x in input().split()]
#import time
#t1= time.time()
S = input()
a= S[0]
b = S[0]
table = [0 for i in range(N+1)]
c = 0
l = 0
#t2 =time.time()
for s in S:
    if s == b:
        c += 1
    else:
        table[l]=c
        c = 1
        l+=1
        if b == '1':
            b = '0'
        else:
            b='1'
#t3 = time.time()
table[l]=c
table = table[0:l+1]
if a =='0':
    N = 2*K+1
    ans = sum(table[0:2*K])
    for i in range(1,len(table),2):
        ans = max(ans,sum(table[i:i+N]))

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

#print(t3-t2)
#print(t2-t1)

Submission status: Time Limit Exceeded

Solution code:
import re

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

def popcnt(n):
  return bin(n).count("1")

cands = []
for xor in range(2 ** len(S)):
  if len(re.split('1+', bin(xor))) != 2:
    continue
  cands.append(xor)

for _ in range(K):
  best_score = max([len(v) for v in re.findall(r'1+', S)])
  best_xor = 0
  for xor in cands:
    if len(re.split('1+', bin(xor))) != 2:
      continue
    
    res = intS ^ xor
    try:
      score = max([len(v) for v in re.findall(r'1+', bin(res))])
    except:
      score = 0
    
    if score > best_score:
      best_score = score
      best_xor = xor
      # print(xor, bin(xor), res, bin(res), _popcnt)
        
  intS = intS ^ best_xor
    
print(max([len(v) for v in re.findall(r'1+', bin(intS))]))

Submission status: Time Limit Exceeded

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

    chunks = []
    prev = S[0]
    count = 0
    for s in S[1:]:
        count += 1
        if prev != s:
            chunks.append(count)
            #if prev == '0':
            #    chunks.append(-1 * count)
            #else:
            #    chunks.append(count)
            count = 0
        prev = s

    chunks.append(count + 1)
    #if prev == '0':
    #    chunks.append(-1 * (count + 1))
    #else:
    #    chunks.append(count + 1)

    if S[0] == '0':
        chunks.insert(0, 0)
    if S[-1] == '0':
        chunks.append(0)
    #if chunks[0] < 0:
    #    chunks.insert(0, 0)
    #if chunks[-1] < 0:
    #    chunks.append(0)

    #print(chunks)

    cands = []
    cand = chunks[0:(2 * K + 1)]
    #print(cand)
    cands.append(sum(cand))

    for i in range(2 * K + 1, len(chunks), 2):
        #print(i)
        cand.append(chunks[i])
        cand.append(chunks[i + 1])
        cand = cand[2:]
        #print(cand)
        cands.append(sum(cand))

    #print(cands)
    print(max(cands))

main()

Submission status: Time Limit Exceeded

Solution code:
"""
python3 c.py < input.txt
"""
import math
import itertools as it
import heapq

N,K=map(int, input().split())
S=input()
T=[S[0]]
U=[1]
for c in S[1:]:
    if c==T[-1]:
        U[-1]=U[-1]+1
    else:
        T.append(c)
        U.append(1) 
M=len(U)
V=[U[0]]
for i in range(1,M):
    V.append(V[-1]+U[i])

X=[]
for l in range(M):
    if T[l]=="0":
        ll=max(0, l-1)
        r=max(l, min(M-1, l+2*(K-1)+1))
        X.append((ll, r))
    else:
        X.append((0,0))
#print(T)
#print(U)
#print(V)
#print(X)
#print([([0]+V)[r+1]-([0]+V)[l] for (l,r) in X])
print(max([([0]+V)[r+1]-([0]+V)[l] for (l,r) in X]))

Submission status: Time Limit Exceeded

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 == '0':
            temp *= -1

        values.append(temp)
        status = S[i]
        temp = 1

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


def get_renzoku(i):
    if values[i] < 0:
        return 2 * K
    else:
        return 2 * K + 1


ans = 0
renzoku = get_renzoku(0)

if len(values) < renzoku:
    for x in values:
        ans += abs(x)
    print(ans)
    exit()

for i in range(len(values)):
    renzoku = get_renzoku(i)
    if i + renzoku > len(values):
        renzoku = len(values) - i

    temp = 0

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

    ans = max(ans, temp)

print(ans)

Submission status: Time Limit Exceeded

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

import numpy as np
line = np.zeros([2*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
        
if ind%2 ==0:
        line[ind] = 0
        ind+=1
line = line[:ind]    
#print(line)

if (len(line)//2)<=k:
    print(n)
else:
    new = line.copy()
    for i in range(1,2*k+1):
        new = new+np.roll(line, i)
    new = new[2*k:]
    new = new[0::2]
    #print(new)
    print(new.max())

Submission status: Time Limit Exceeded

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

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

c = c + [0]
ans = 1

if s[0] == "1":
  for i in range(0, len(c), 2):
    if i+2*k+1 > len(c):
      ans = max(ans, sum(c[i:]))
    else:
      ans = max(ans, sum(c[i:i+2*k+1]))
else:
  c = [0] + c
  for i in range(0, len(c), 2):
    if i+2*k+1 > len(c):
      ans = max(ans, sum(c[i:]))
    else:
      ans = max(ans, sum(c[i:i+2*k+1]))

print(ans)

Submission status: Time Limit Exceeded

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

b = []
l = []
count = 1

for i in range(len(s)):
  try:
    if s[i] == s[i+1]:
      count = count + 1
    else:
      b.append(int(s[i]))
      l.append(count)
      count = 1
  except:
    b.append(int(s[i]))
    l.append(count)

# print(b)
# print(l)

if len(b) / 2 <= k:
  print(sum(l))
else:
  m = 0 
  if b[0] == 1:
    for i in range(len(b) // 2 - k + 1):
      st = max(0, i * 2)
      en = min(i * 2 + k * 2 + 1, len(b)) 
#       print(st, en, l[st:en])
      m = max(m, sum(l[st:en]))

  else:
    for i in range((len(b) + 1) // 2 - k + 1):
      st = max(0, i * 2 - 1)
      en = min(i * 2 + k * 2, len(b)) 
#       print(st, en, l[st:en])
      m = max(m, sum(l[st:en]))

  print(m)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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

stand = []
reverse = []
state = None
count = 0
tmp = None
for i in S:
	if i == "0":
		state = "stand"
	else:
		state = "reverse"
	if tmp == "stand" and state == "reverse":
		stand.append(count)
		count = 1
	elif tmp == "reverse" and state == "stand":
		reverse.append(count)
		count = 1
	else: # 状態が前と同じ
		count += 1
	tmp = state
if state == "stand":
	stand.append(count)
else:
	reverse.append(count)

if "0" not in S:
	print(len(S))
else:
	if K >= len(stand): # 全員逆立ちにできる
		print(len(S))
	else:
		if len(stand) > len(reverse):
			reverse.append(0)
			reverse.insert(0, 0)
		if len(stand) == len(reverse) and S[0] == "0":
			reverse.insert(0, 0)
		if len(stand) == len(reverse) and S[0] == "1":
			reverse.append(0)
		# print(stand)
		# print(reverse)
		max_ = 0
		for i in range(max(1, 1+len(reverse)-(K+1))):
			# print(reverse[i:i+K+1],stand[i:i+K])
			tmp = sum(reverse[i:i+K+1])+sum(stand[i:i+K])
			if tmp > max_:
				max_ = tmp
		print(max_)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
n, k = map(int, input().split())
s = input()

hsc = []
pre = s[0]
cnt = 0
for c in s:
    if c == pre:
        cnt += 1
    else:
        if pre == '0':
            hsc.append(-cnt)
        else:
            hsc.append(cnt)
        pre = c
        cnt = 1
if pre == '0':
    hsc.append(-cnt)
else:
    hsc.append(cnt)

max_hsc = []

for i, c in enumerate(hsc):
    cnt = 0
    _k = 0
    for _c in hsc[i:]:
        if _c < 0:
            _k += 1
        if _k > k:
            break
        cnt += abs(_c)
    max_hsc.append(cnt)

print(max(max_hsc))

Submission status: Time Limit Exceeded

Solution code:
N = list(map(int, input().split()))
x = input()
res = 0

a0 = list(x.split("1"))
a1 = list(x.split("0"))

l0 = [len(a0[i]) for i in range(len(a0)) if len(a0[i]) > 0]
l1 = [len(a1[i]) for i in range(len(a1)) if len(a1[i]) > 0]

if x[0] == "0":
    l1.insert(0,0)
if x[len(x)-1] == "0":
    l1.append(0)

for i in range(len(l1)):
    if res < sum(l1[i:i+N[1]+1]) + sum(l0[i:i+N[1]]):
        res = sum(l1[i:i+N[1]+1]) + sum(l0[i:i+N[1]])

print(res)

Submission status: Time Limit Exceeded

Solution code:
#https://atcoder.jp/contests/abc124/tasks/abc124_d


NK = [int(i) for i in input().split()]
S = str(input())
N = NK[0]
K = NK[1]
Sarray = list(S)
for i in range(len(Sarray)):
    Sarray[i] = int(Sarray[i])
    if Sarray[i] == 0:
        Sarray[i] = -1

mode = Sarray[0]
a = [0]
for i in range(len(Sarray)):
    c = (len(a) - 1) % 2
    b = (-1)** c * mode
    if Sarray[i] != b:
        a.append(0)
    a[len(a) - 1] += 1

#print(mode,a)

#aはmodeを先頭に同じのが何個続くか

adjust = 0
if mode == 1:
    adjust = 1

tmp = 0
count = 0

for l in range(adjust,len(a) + 1,2):
    for i in range(l, l + 2 * K - 1):
        if i < len(a):
            tmp += a[i]
        else:
            break
    
    if l > 0:
        #print('under+')
        tmp += a[l - 1]
    if l + 2 * K - 1 < len(a):
        #print('over+')
        tmp += a[l + 2 * K - 1]
    #print(tmp)

    if count < tmp:
        count = tmp
    tmp = 0

print(count)

Submission status: Time Limit Exceeded

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

# 奇数番目は1のカタマリの人数　偶数番目は0のカタマリの人数 両端は必ず1のカタマリの人数
now_state, now_count = '1', 0
L = []
Ladd = L.append
for i in range(len(S)):
  if S[i] == now_state:
    now_count += 1
  else:
    Ladd(now_count)
    # reset
    now_count = 1
    now_state = '1' if now_state == '0' else '0'
Ladd(now_count)
if now_state == '0':
  Ladd(0)

#print(L)
# 0の塊をj個ひっくり返す
# j==1のとき101の3個の和の最大
# j==2のとき10101の5個の和の最大
# j==jのとき101...1のj*2+1個の和の最大

def evenngram(n, _list):
  return [_list[i:i+n] for i in range(len(_list)-n+1) if i%2==0]

now_max = 0
j = min(int((len(L)-1)/2), K) # 0のカタマリをひっくり返せるだけひっくり返す
tmp = evenngram(j*2+1, L)
tmp = [sum(t) for t in tmp]
tmp = max(tmp) if len(tmp) > 0 else 0
now_max = max(tmp, now_max)
print(now_max)

Submission status: Time Limit Exceeded

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

start = 0
rl = []
nm = 0
for i in range(N):
  t = 0
  c = 0
  k = K
  for s in S[i:]:
    if k == 0 and s == 0:
      break
    c+=1
    if(s == 0 and t == 0):
      t = 1
    elif(s == 1 and t == 1):
      k -= 1
      t = 0
  rl.append(c)
  if(i+max(rl) >= N):
    break
print(max(rl))

Submission status: Time Limit Exceeded

Solution code:
def hanntenn(n):
    if n=="0":
        return "1"
    else:
        return "0"
from itertools import combinations

def numcheck(s):
    maxlen = 0
    j = 0
    for i in range(len(s)):
        if i >= len(s):
            return maxlen
        
        if s[i] == "1":
            j = i
            while(j+1 < len(s) and s[j+1] == "1"):
                j+=1
            _len = j-i+1
            if _len >= maxlen:
                maxlen = _len
            j+=1
        else:
            j+=1
            
    return maxlen

def zerocheck(s):
    pare = []
    j = 0
    for i in range(len(s)):
        i = j
        if i >= len(s):
            return pare
        
        if s[i] == "0":
            j = i
            while(j+1 < len(s) and s[j+1] == "0"):
                j+=1
            pare.append((i,j))
            j+=1
        else:
            j+=1
    return list(set(pare))
  
import copy
n,k = map(int, input().split())

s = input()
lists = list(s)

zerolists = zerocheck(s)
max_len = 0
for i in range(len(zerolists)):
    _lists = copy.copy(lists)
    for j in range(i,i+k):
        if j >= len(zerolists):
            continue
        for l in range(zerolists[j][0],zerolists[j][1]+1):
            _lists[l] = "1"
        _len = numcheck(_lists)
        if _len >= max_len:
            max_len = _len
            if max_len == len(lists):
              break
if numcheck(lists) >= max_len:
    max_len = numcheck(lists)
print(max_len)

Submission status: Time Limit Exceeded

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

# 奇数番目は1のカタマリの人数　偶数番目は0のカタマリの人数 両端は必ず1のカタマリの人数
now_state, now_count = '1', 0
L = []
for i in range(len(S)):
  if S[i] == now_state:
    now_count += 1
  else:
    L.append(now_count)
    # reset
    now_count = 1
    now_state = '1' if now_state == '0' else '0'
L.append(now_count)
if now_state == '0':
  L.append(0)

#print(L)
# 0の塊をj個ひっくり返す
# j==1のとき101の3個の和の最大
# j==2のとき10101の5個の和の最大
# j==jのとき101...1のj*2+1個の和の最大

def evenngram(n, _list):
  return [_list[i:i+n] for i in range(len(_list)-n+1) if i%2==0]

now_max = 0
j = min(int((len(L)-1)/2), K) # 0のカタマリをひっくり返せるだけひっくり返す
tmp = evenngram(j*2+1, L)
tmp = [sum(t) for t in tmp]
tmp = max(tmp) if len(tmp) > 0 else 0
now_max = max(tmp, now_max)
print(now_max)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
s = input()
s2 = [["1", 0, 0]]
zero = 0
one_count = 1
for i, c in enumerate(s):
    if s2[-1][0] == c:
        s2[-1][2] += 1
    else:
        s2.append([c, i, 1])
        zero += (1 - int(c))
        if c == "1":
            one_count += 1
if zero <= k:
    print(n)
    exit()
if s2[-1][0] == "0":
    s2.append(["1", len(s)-1, 0])
    one_count += 1
ans = -1
sum_ = -1
for i in range(one_count - k):
    a = 0
    if sum_ < 0:
        for e in s2[i*2:(i+k)*2+1]:
            a += e[2]
    else:
        sum_ = sum_ - s2[i-2][2] + s2[(i+k)*2+1][2]
    if ans < a:
        ans = a
print(ans)

Submission status: Time Limit Exceeded

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]

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: Time Limit Exceeded

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
table = table[0:l+1]
if a =='0':
    N = 2*K+1
    ans = sum(table[0:2*K])
    for i in range(1,len(table),2):
        ans = max(ans,sum(table[i:i+N]))

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

Submission status: Time Limit Exceeded

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

l = []
for i in range(N):
  if i == 0 or S[i - 1] != S[i]:
    l.append(1)
  else:
    l[-1] += 1

if S.count("1") == N or S.count("0") == N:
  print(N)
else:
  ans = 0
  for i in range(len(l)):
    cnt = 0
    if S[0] == "0" and i == 0:
      for j in range(K * 2):
        cnt += l[j]
        if j == len(l) - 1:
          break
    elif S[0] == "0" and i % 2 == 1 or S[0] == "1" and i % 2 == 0:
      for j in range(i, i + K * 2 + 1):
        cnt += l[j]
        if j == len(l) - 1:
          break  
    ans = max(ans, cnt)
  print(ans)

Submission status: Time Limit Exceeded

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

if s[0] == "1":
    retu = "whiteblack"
else:
    retu = "blackwhite"


count = 0
pre_person = s[0]
groups = []
for i in range(n):
    person = s[i]

    if person != pre_person:
        groups.append(count)
        count = 0
        pre_person = person
    count += 1
groups.append(count)


maxscore1 = 0
if retu == "whiteblack":
    score1 = 0
    blackgroups = len(groups)//2
    if k < blackgroups:
        for i in range(blackgroups-k+1):
            start_index = 2*i + 1
            score1 = groups[start_index-1]
            for j in range(k):
                score1 += groups[start_index+2*j]
                if start_index + 2*j+1 < len(groups):
                    score1 += groups[start_index+2*j+1]
            maxscore1 = max(score1, maxscore1)
    else:
        maxscore1 = n

else:
    score1 = 0
    blackgroups = len(groups) - len(groups)//2
    if k < blackgroups:
        for i in range(blackgroups-k+1):
            start_index = 2*i
            if start_index-1 >= 0:
                score1 = groups[start_index-1]
            else:
                score1 = 0
            for j in range(k):
                score1 += groups[start_index+2*j]
                if start_index + 2*j+1 < len(groups):
                    score1 += groups[start_index+2*j+1]
            maxscore1 = max(score1,maxscore1)
    else:
        maxscore1 = n

print(maxscore1)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
S = input()
l = []
a = 0
if S[0] == '1':
	a += 1
else:
	l.append(a)
	a += 1
for i in range(1, N, 1):
	if S[i] == S[i - 1]:
		a += 1
	else:
		l.append(a)
		a = 1
l.append(a)
if S[N - 1] == '0':
	l.append(0)
if (len(l) - 1) // 2 + 1 - K < 1:
	print(N)
else:
	m = []
	for k in range((len(l) - 1) // 2 + 1 - K):
		m.append(sum(l[2 * k:2 * k + 2 * K + 1]))
	print(max(m))

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
s = list(input())
if s[0] == '0':
  s0 = -1
  s1 = 0
else:
  s0 = 0
  s1 = 1
s_ = []
for i in range(1,N):
  if s0 < 0 and s[i]=='1':
    s_.append(s0)
    s0 = 0
    s1 = 1
  elif s1 > 0 and s[i] == '0':
    s_.append(s1)
    s0 = -1
    s1 = 0
  elif s0 <= 0 and s1 == 0 and s[i] == '0':
    s0 -= 1
  elif s1 >= 0 and s0 == 0 and s[i] == '1':
    s1 += 1
if s0 < 0:
  s_.append(s0)
elif s1 > 0:
  s_.append(s1)
ans = 0
if len([i for i in s_ if i < 0])<=K:
  print(sum([abs(i) for i in s_]))
else:
  for j in range(len(s_)):
    count = 0
    ans_tmp = 0
    for k in range(j,len(s_)):
      if s_[k] < 0:
        count+=1
      ans_tmp+=abs(s_[k])
      if count == K+1:
        ans_tmp-=abs(s_[k])
        break
    if ans < ans_tmp:
      ans = ans_tmp
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

l = [list(np.repeat(0, K)), list(np.repeat(0, K))]
ans = []
k = [int(s) for s in S]
v0 = 1 if k[0] == 0 else 0
v1 = 1 if k[0] == 1 else 0
for i in range(1, N):
    if (k[i]==0) & (k[i-1]==0):
        v0 += 1
    elif (k[i]==1) & (k[i-1]==0):
        l[0].append(v0)
        v0 = 0
        v1 += 1
    elif (k[i]==0) & (k[i-1]==1):
        l[1].append(v1)
        v1 = 0
        v0 += 1
        
        a = sum(l[0][-K:]+l[1][-K-1:])
        ans.append(a)    
    else:
        v1 += 1
        
for i, v in enumerate([v0, v1]):
    if v > 0:
        l[i].append(v)

if len(l[0])-K <= K:
    print(N)

else:
    a = sum(l[0][-K:]+l[1][-K-1:])
    ans.append(a)
    print(max(ans))

Submission status: Time Limit Exceeded

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

C = []
c = 1
s = S[0]
for i in range(len(S)):
    if i == 0:
        continue
    if S[i] == S[i-1]:
        c += 1
    else:
        C.append((c, s))
        c = 1
        s = '1' if s == '0' else '0'

C.append((c, s))

ans = 0
for i in range(len(C)):
    flg = False
    count = 0
    for j in range(len(C) - i):
        if C[i+j][1] == '0':
            count += 1
            if count > K:
                ans = max(ans, sum(map(lambda x: x[0], C[i: i+j])))
                flg = True
                break
    if not flg:
        ans = max(ans, sum(map(lambda x: x[0], C[i:])))
print(ans)

Submission status: Time Limit Exceeded

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

start = 0
rl = []
nm = 0
for i in range(N):
  t = 0
  c = 0
  k = K
  for s in S[i:]:
    if k == 0 and s == 0:
      break
    c+=1
    if(s == 0 and t == 0):
      t = 1
    elif(s == 1 and t == 1):
      k -= 1
      t = 0
  rl.append(c)

print(max(rl))

Submission status: Time Limit Exceeded

Solution code:
import sys
N, K = map(int, input().split())
S = sys.stdin.readline()
S = S[:-1]
check = S[0]
if check == '0':
    Slist = [0]
else:
    Slist = []
count = 1
for i in range(len(S)-1):
    if S[i+1] == check:
        count += 1
    else:
        Slist.append(count)
        check = S[i+1]
        count = 1
Slist.append(count)

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

if K >= int((len(Slist)-1)/2):
    print(sum(Slist))
else:
    sumlist = [sum(Slist[2*i:2*K+1+2*i]) for i in range(int((len(Slist)-2*K+1)/2))]
    print(max(sumlist))

Submission status: Time Limit Exceeded

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

list1 = []
list0 = []
app1 = list1.append
app0 = list0.append
pre_num = 1
count = 0
for i in range(N):
    if S_list[i] == pre_num:
        count += 1
    else:
        if S_list[i] == 0:
            app1(count)
        else:
            app0(count)
        count = 1
        pre_num = S_list[i]

if count != 0:
    if pre_num == 0:
        app0(count)
    else:
        app1(count)
        
if S_list[-1] == 1:
    app0(0)
    
        
ans = 0

if K >= len(list0):
    ans = N
else:
    for i in range(len(list0)- K + 1):
        num1 = sum(list1[i:i+K])
        num0 = sum(list0[i:i+K])
        ex = 0
        if i+K < len(list0):
            ex = list1[i+K]
        ans = max(ans, num0 + num1 + ex)
    
print(ans)

Submission status: Time Limit Exceeded

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

A = []

if N == 1:
    print(1)
else:
    cnt = 0

    # 0から始まるなら最初に逆立ちしている人を追加する
    if S[0] == "0":
        A.append(0)

    for i in range(len(S)):
        if i == 0:
            cnt += 1
            continue

        if S[i] == S[i-1]:
            cnt += 1
        else:
            A.append(cnt)
            cnt = 1

    A.append(cnt)

    maxLen = 0

    for i in range(len(A)):
        if (i % 2 == 1):
            continue
        maxLen = max(maxLen,sum(A[i : i + K*2 + 1]))

    print(maxLen)

Submission status: Time Limit Exceeded

Solution code:
n, k=map(int, input().split())
s=list(map(int, list(input())))
renzoku_list=[0]
sum=1
before=s[0]
for i in range(1, n):
    if s[i]==before:
        sum=sum+1
        before=s[i]
    else:
        renzoku_list.append(sum)
        sum=1
        before=s[i]
renzoku_list.append(sum)
renzoku_list.append(0)
result_list=[]
length=len(renzoku_list)

max=0
if s[0]==0 and -(-(length-2)//2)<=k:
    print(n)
elif s[0]==1 and (length-2)//2<=k:
    print(n)
elif s[0]==0:
    for i in range(0, length-(2*k+1)+1, 2):
        result=0
        for j in range(i, i+2*k+1):
            result=result+renzoku_list[j]
        if max<=result:
            max=result
    print(max)
elif s[0]==1:
    for i in range(1, length-(2*k+1)+1, 2):
        result=0
        for j in range(i, i+2*k+1):
            result=result+renzoku_list[j]
        if max<=result:
            max=result
    print(max)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n, k = map(int, input().split())
S = input()
blocks = [(k, len(list(v))) for k, v in itertools.groupby(S)]
res = 0
i = 0
if blocks[i][0] == '0':
  res = max(res, sum([b[1] for b in blocks[i:i+2*k]]))
  i += 1

while i < len(blocks):
  res = max(res, sum([b[1] for b in blocks[i:i+2*k+1]]))
  i += 2
print(res)

Submission status: Time Limit Exceeded

Solution code:
NK = [int(i) for i in input().split()]
S = str(input())
N = NK[0]
K = NK[1]
Sarray = list(S)
for i in range(len(Sarray)):
    Sarray[i] = int(Sarray[i])
    if Sarray[i] == 0:
        Sarray[i] = -1

mode = Sarray[0]
a = [0]

for i in range(len(Sarray)):
    b = (-1) ** (len(a) - 1) * mode
    if Sarray[i] != b:
        a.append(0)
    a[len(a) - 1] += 1

#print(mode,a)

#aはmodeを先頭に同じのが何個続くか

adjust = 0
if mode == 1:
    adjust = 1

tmp = 0
count = 0

for l in range(adjust,len(a) + 1,2):
    for i in range(l, l + 2 * K - 1):
        if i < len(a):
            tmp += a[i]
            #print(l,i,tmp)
        else:
            #print('break')
            break
    if l > 0:
        #print('under+')
        tmp += a[l - 1]
    if l + 2 * K - 1 < len(a):
        #print('over+')
        tmp += a[l + 2 * K - 1]
    #print(tmp)

    if count < tmp:
        count = tmp
    tmp = 0

print(count)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
s = input()
s2 = [["1", 0, 0]]
zero = 0
one_count = 1
for i, c in enumerate(s):
    if s2[-1][0] == c:
        s2[-1][2] += 1
    else:
        s2.append([c, i, 1])
        zero += (1 - int(c))
        if c == "1":
            one_count += 1
if zero <= k:
    print(n)
    exit()
if s2[-1][0] == "0":
    s2.append(["1", len(s)-1, 0])
    one_count += 1
ans = -1
for i in range(one_count - k):
    a = 0
    for e in s2[i*2:(i+k)*2+1]:
        a += e[2]
    if ans < a:
        ans = a
print(ans)

Submission status: Time Limit Exceeded

Solution code:

def read_input():
    n, k = map(int, input().split())
    s = list(map(int, list(str(input()))))

    return n, k, s


# 0, 1, ....を(0, n1), (1, n2)みたいな形にする
def convert_01(s):
    result = []

    result.append([s[0], 1])
    for ss in s[1:]:
        if result[-1][0] == ss:
            result[-1][1] += 1
        else:
            result.append([ss, 1])

    return result


# index以降の要素、かつ0の数がKを下回るサブリストにある要素をカウントする
def get_elements_in_subliist(r, index, k):
    count = 0

    zeros = 0
    for i in range(index, len(r)):
        if r[i][0] == 0:
            zeros += 1

        if r[i][0] == 0 and zeros > k:
            return count

        count += r[i][1]

    return count




if __name__ == '__main__':
    n, k, s = read_input()

    r = convert_01(s)

    max_count = 0
    for i in range(n):
        t = get_elements_in_subliist(r, i, k)
        if t > max_count:
            max_count = t

    print(max_count)

Submission status: Time Limit Exceeded

Solution code:
import math

N,K=map(int,input().split())
S=input()
L=[]
seq=0
prev='2'
for i in S:
  if i == prev:
    seq += 1
  else:
    L.append(seq)
    prev = i
    seq = 1
L.append(seq)
L.append(0)

L_cum = [0]*(len(L)+1)
for i in range(len(L)):
  L_cum[i]=sum(L[0:i+1])

if S[0] == '0':
  num_0 = math.ceil((len(L)-2)/2)
  if num_0<=K:
    ans=N
  else:
    rev=[0]*(num_0-K+1)
    for i in range(num_0-K+1):
      rev[i]=L_cum[2*(K+i)]-L_cum[i*2-1]
    ans=max(rev)
else:
  num_0 = math.floor((len(L)-2)/2)
  if num_0<=K:
    ans=N
  else:
    rev=[0]*(num_0-K+1)
    for i in range(num_0-K+1):
      rev[i]=L_cum[2*(K+i)+1]-L_cum[2*i]
    ans=max(rev)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
people = list(input())
lst = []
count = 0
flag = people[0]
if flag == '1':
	lst.append(0)
for i in range(len(people)):
	if i == len(people) - 1:
		lst.append(count + 1)
	elif people[i] == flag and people[i+1] != flag:
		lst.append(count + 1)
		count = 0
		flag = people[i + 1]
	else:
		count += 1

maximum = 0
l = len(lst)
for i in range(l):
	if i % 2 == 0:
		end = i+2*K
		if i != 0:
			maximum = max(maximum, sum(lst[i-1:end]))
		else:
			maximum = max(maximum, sum(lst[i:end]))
		if end > l:
			break
	else:
		end = 2*K+1
		maximum = max(maximum, sum(lst[i:end]))
		if end > l:
			break
print(maximum)