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:
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
INF = float('inf')
MOD = 10**9+7
dy = [0,1,0,-1]
dx = [1,0,-1,0]
ddy = [0,1,1,1,0,-1,-1,-1]
ddx = [1,1,0,-1,-1,-1,0,1]

n,k = map(int,input().split())
S = input()+'!'

get = [0]
tmp = 1
for i in range(1,n+1):
    if S[i] == S[i-1]:
        tmp += 1
    else:
        get.append(tmp)
        tmp = 1

get = get + [0,0,0,0,0]

for i in range(1,len(get)):
    get[i] += get[i-1]

res = 0
if S[0] == '0':
    for i in range(len(get)-2*k-1):
        if i%2 == 0:
            ans = get[i+2*k]-get[i]
        else:
            ans = get[i+2*k+1]-get[i]
        if res <= ans:
            res = ans
else:
    for i in range(len(get)-2*k-1):
        if i%2 == 0:
            ans = get[i+2*k+1]-get[i]
        else:
            ans = get[i+2*k]-get[i]
        if res <= ans:
            res = ans

print(res)

Submission status: Wrong Answer

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

s = list(str(input()))

first_index=0
last_index=0

res = 0
for f in range (first_index, n):
  for l in range (last_index, n):
    if f < l:
      continue
    check = 0
    for i in (f, l):
      if s[i] == 0:
        check += 1
    if check <= k:
      if l-f > res:
        res = l-f

print(res)

Submission status: Wrong Answer

Solution code:
n,k = (int(i) for i in input().split())
s = input()
li_0 = [0]*k
li_1 = [0]*(k+1)
ind_0 = 0
ind_1 = 0
flag = -1
cnt = 0
ans = 0

if s[0] == '0':
  flag = 0
else:
  flag = 1

for i in s:
  if flag == i:
    cnt += 1
  else:
    if flag == '1':
      li_1[ind_1] = cnt
      flag = i
      cnt = 1
      if ind_1 < k:
        ind_1 += 1
      else:
        ind_1 = 0
    else:
      li_0[ind_0] = cnt
      flag = i
      cnt = 1
      if ind_0 < k-1:
        ind_0 += 1
      else:
        ind_0 = 0
  ans = max(ans,sum(li_0)+sum(li_1))

if flag == '1':
  li_1[ind_1] = cnt
else:
  li_0[ind_0] = cnt
  li_1[ind_1] = 0

ans = max(ans,sum(li_0)+sum(li_1))

print(ans)

Submission status: Wrong Answer

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

z_list = []
o_list = []
zero = 0
one = 0
most_l = s[0]
most_r = s[N - 1]
prev = s[0]
if prev == '0':
    zero += 1
else:
    one += 1
s.pop(0)
for c in s:
    if c == '0':
        zero += 1
    else:
        one += 1
    if prev != c:
        if prev == '0':
            z_list.append(zero)
            zero = 0
        else:
            o_list.append(one)
            one = 0
    prev = c
z_list.append(zero)
o_list.append(one)

# print(z_list)
# print(o_list)

z_len = len(z_list)
o_len = len(o_list)
if most_l == '0':
    real_k = K
else:
    real_k = K + 1

sum = 0
for k in range(real_k):
    if k < z_len:
        sum += z_list[k]
    if k < o_len:
        sum += o_list[k]

max = sum

k_judge = real_k
for i in range(N):
    if most_r == '0' and most_l == '1' and i + k_judge - 1 == z_len:
        real_k -= 1
    if i + real_k < z_len:
        sum -= z_list[i]
        sum += z_list[i + real_k]
    if i + real_k < o_len:
        sum -= o_list[i]
        sum += o_list[i + real_k]
    if max < sum:
        max = sum

print(max)

Submission status: Wrong Answer

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

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

    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from itertools import accumulate
N, K  = map(int, input().split())
ans = 0
num = 0
S = input()
a = S.split('1')
b = S.split('0')
ls = []
for x in a:
    if len(x) != 0:
        ls.append(len(x))
c = [0] + list(accumulate(ls))
ls_ = []
for x in b:
    if len(x) != 0:
        ls_.append(len(x))
d = [0] + list(accumulate(ls_))

if len(c) <= K:
    print(N)
    sys.exit()

if len(c) == len(d):
    for x, y, u, t in zip(c, c[K:], d, d[K+1:]):
        ans = max(ans, y-x+t-u)
    print(ans)
elif len(c) == len(d)+1:
    r = d[-1]
    d.append(r)
    for x, y, u, t in zip(c, c[K:], d, d[K:]):
        ans = max(ans, y-x+t-u)
    print(ans)
elif len(c) == len(d)-1:
    q = c[-1]
    c.append(q)
    for x, y, u, t in zip(c, c[K:], d, d[K+1:]):
        ans = max(ans, y-x+t-u)
    print(ans)

Submission status: Wrong Answer

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

if len(s) == 1:
    print(1)
else:
    # 最初に塊を把握
    chunk_len = []
    prev = s[0]
    cnt = 1
    max_score = 0
    for x in s[1:]:
        if x == prev:
            cnt += 1
        else:
            if prev == '0':
                prev = '1'
            else:
                prev = '0'
                max_score = max(max_score, cnt)
            chunk_len.append(cnt)
            cnt = 1
            
    chunk_len.append(cnt)
    n_chunk = len(chunk_len)

    n_odd_chunk = int(n_chunk / 2)
    
    if s[0] == '1':
        # 偶数番目を順番に入れ替えていく
        if n_odd_chunk - k <= 0:
            print(len(s))
        else:
            for i in range(n_odd_chunk - k + 1):
                score = sum(chunk_len[2*i:2*(i+k)+1])
                if max_score < score:
                    max_score = score
            
            print(max_score)
    else:
        # 奇数番目を順番に入れ替えていく
        if n_odd_chunk - k <= 0:
            print(len(s))
        else:
            for i in range(int(n_chunk / 2) - k + 1):
                if i == 0:
                    score = sum(chunk_len[:2*(i+k)])
                else:
                    score = sum(chunk_len[2*i-1:2*(i+k)])

                if max_score < score:
                    max_score = score
        
            print(max_score)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
s = input()
s0 = []
s1 = []
str_s = s[0]
str_num = 0
for i in range(n-1):
    if str_s != s[i+1] and str_s == "0":
        s0.append(i+1 - str_num)
        str_num = i+1
        str_s = "1"
    elif str_s != s[i+1] and str_s == "1":
        s1.append(i+1 - str_num)
        str_num = i+1
        str_s = "0"
if str_s == "0":
    s0.append(n - str_num)
else:
    s1.append(n - str_num)
if len(s0) >= len(s1):
    s1.append(0)
if len(s0) >= len(s1):
    s1.insert(0, 0)
for i in range(k):
    if(len(s0) == 0):
        break
    max_1 = 0
    for j in range(len(s0)):
        if(s1[j]+s0[j]+s1[j+1] > max_1):
            max_1 = s1[j]+s0[j]+s1[j+1]
            max_list = j
    s0.pop(max_list)
    s1.pop(max_list)
    s1.pop(max_list)
    s1.insert(max_list, max_1)
print(max(s1))

Submission status: Wrong Answer

Solution code:
import re
import numpy as np
N, K = [int(item) for item in re.split(r"\s", input())]
S = [int(item) for item in list(input())]

if sum(S) == len(S) or sum(S) == 0:
    print(len(S))
else:
    S = S + [2]

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

    count = np.diff(np.array(index)).tolist()

    if S[i] == 0:
        count = [0] + count

    cumsum = [0] + np.cumsum(count).tolist()
    c_len = len(cumsum)
    win = min(2 * K + 1, c_len - 1)
    print(max([cumsum[i + win] - cumsum[i] for i in range(0, c_len - win, 2)]))

Submission status: Wrong Answer

Solution code:
import bisect
from collections import deque
from collections import defaultdict
from fractions import gcd
#from math import factorial
from math import sqrt
from math import ceil
from itertools import permutations
from heapq import *

N,K=map(int,input().split())
S=input()
if S[-1]=="0":
    S+="1"
else:
    S+="0"
List=[]
ini=S[0]
now=0
zeronum=0
for i in range(N+1):
    if S[i]==ini:
        now+=1
        continue
    else:
        if ini=="1":
            List.append(now)
        else:
            List.append(now*(-1))
            zeronum+=1
        ini=S[i]
        now=1
if List[0]<0:
    List.insert(0,0)
N=len(List)
sum=0
SUM=0

if zeronum<=K:
    print(N)
    quit()
for i in range(2*K+1):
    if i%2==1:
        sum+=List[i]*(-1)
    else:
        sum+=List[i]
SUM=max(sum,SUM)

for i in range(6):
    List.append(0)
ind=0
for i in range(K+1,N//2+3):

    sum+=-List[ind]+List[ind+1]-List[2*i-1]+List[2*i]
    ind+=2
    SUM=max(sum,SUM)
print(SUM)

Submission status: Wrong Answer

Solution code:
times = input().split()
N = int(times[0])
K = int(times[1])
S = input()


def one_counter(S):
    tmp = 0
    high = 0
    for z in S:
        if z == "1":
            tmp += 1
        else:
            if tmp > high:
                high = tmp
                tmp = 0
            else:
                tmp = 0
    if tmp > high:
        high = tmp
    return high


for i in range(K):
    if S.find("0") == -1:
        break
    zero_counter = []
    start_index = -1
    end_index = -1
    diff = 0
    for j, value in enumerate(S):
        if value == "0" and start_index == -1:
            start_index = j
        elif value == "1" and start_index != -1:
            end_index = j
            diff = end_index - start_index
            zero_counter.append([start_index, end_index, diff])
            start_index = -1
            end_index = -1
            diff = 0
    high_score = one_counter(S)
    high_S = S
    for k in zero_counter:
        S_f = S[:k[0]]
        S_b = S[k[1]:]
        ones = "1"*k[2]
        tmp_S = S_f+ones+S_b
        score = one_counter(tmp_S)
        if score > high_score:
            high_S = tmp_S
    S = high_S


print(one_counter(S))

Submission status: Wrong Answer

Solution code:
import re, copy


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

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

def get_longest_1_in_str(string):
    res = pattern_1.findall(string)
    res_list = [len(s) for s in res]
    return max(res_list)

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


length_list = []
for i in range(0,len(list_0)):
    new_string_list = copy.copy(input_list)
    for j in range(k):
        if i + j >= len(list_0): break
        new_string_list[list_0[i+j][0]:list_0[i+j][0] + list_0[i+j][1]] = ['1' for j in range(0, list_0[i+j][1])]


    m = get_longest_1_in_str("".join(new_string_list))
    length_list.append(m)

if len(length_list) == 0:
    print(1)
else:
    print(max(length_list))

Submission status: Wrong Answer

Solution code:
from sys import stdin
from collections import deque, defaultdict as ddic
from itertools import combinations, permutations, product
import bisect
import heapq

rs = lambda: stdin.readline().strip()
ri = lambda: int(rs())
rsl = lambda: stdin.readline().split()
rim = lambda: map(int, rsl())
ril = lambda: list(rim())

n, k = rim()
s = list(rs())
zeros = []
temp = []
instreak = False
for i, char in enumerate(s):
    if char == '0':
        if not instreak:
            zeros.append(i)
            instreak = True
    else:
        instreak = False

# 1111111
if not zeros:
    print(len(s))
else:
    zeros = [-1] + zeros + [len(s)]
    maximum = 0
    index = 0
    left = zeros[index]
    if k == 0:
        # just count 1
        streak, maximum = 0, 0
        for i, char in enumerate(s):
            if char == '1':
                streak += 1
            else:
                if streak > maximum:
                    maximum = streak
                streak = 0

            if i == len(s)-1 and char == '1':
                if streak > maximum:
                    maximum = streak
    else:
        if k+1 >= len(zeros):
            k = len(zeros)-2
        for i in range(k+1, len(zeros)):
            right = zeros[i]
            streak = right - 1 - left
            if streak > maximum:
                maximum = streak
            index += 1
            left = zeros[index]

    print(maximum)

Submission status: Wrong Answer

Solution code:
import heapq
class PrioritySet(object):
    def __init__(self):
        self.heap = []
        self.set = set()
    def add(self, pri, d):
        heapq.heappush(self.heap, (pri, d))
        if not d in self.set:
            self.set.add(d)
    def get(self):
        while True:
            pri, d = heapq.heappop(self.heap)
            if d in self.set:
                self.set.remove(d)
                return (pri, d)
    def empty(self):
        return len(self.heap) == 0

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

zero_potentials = []
zero_chunks = []
one_chunks = []
zero_chunk = 0
one_chunk = 0
for s in S:
    if s == '1':
        one_chunk += 1
        if zero_chunk > 0:
            zero_chunks.append(zero_chunk)
            zero_potential = [0, zero_chunk, 0]
            if len(one_chunks) > 0:
                zero_potential[0] = one_chunks[-1]
            zero_potentials.append(zero_potential)
            zero_chunk = 0
    elif s == '0':
        zero_chunk += 1
        if one_chunk > 0:
            one_chunks.append(one_chunk)
            if len(zero_potentials) > 0:
                zero_potentials[-1][2] = one_chunk
            one_chunk = 0

if zero_chunk > 0:
    zero_chunks.append(zero_chunk)
    zero_potential = [0, zero_chunk, 0]
    if len(one_chunks) > 0:
        zero_potential[0] = one_chunks[-1]
    zero_potentials.append(zero_potential)

if one_chunk > 0:
    if len(zero_potentials) > 0:
        zero_potentials[-1][2] = one_chunk

pset = PrioritySet()
for i in range(len(zero_potentials)):
    pset.add(-sum(zero_potentials[i]), i)

result = len(S)
for k in range(K):
    if pset.empty():
        break
    pri, i = pset.get()

    if i > 0:
        zero_potentials[i-1][2] = -pri
        pset.add(-sum(zero_potentials[i-1]), i-1)
    if i < len(zero_potentials)-1:
        zero_potentials[i+1][0] = -pri
        pset.add(-sum(zero_potentials[i+1]), i+1)
    result = -pri

print(result)

Submission status: Wrong Answer

Solution code:
N,K = [int(i) for i in input().split()]
S = list(map (int, list(input())))
start = S[0]
row = []
state = [0,start]
for i in S:
    if i == start:
        state[0] += 1
    else:
        row.append(state)
        start = i
        state = [1,i]
row.append(state)
ans = []
for i in range(max(len(row)-K*2,1)):
    if row[i][1] == 1:
        ans.append(sum([row[i][0] for i in range(i,min(K*2+i+1,len(row)))]))
    else:
        ans.append(sum([row[i][0] for i in range(i,min(K*2+i,len(row)))]))
print(max(ans))

Submission status: Wrong Answer

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

s = list(str(input()))

first_index=0
last_index=0

res = 0
for f in range (first_index, n):
  for l in range (last_index, n):
    if first_index < last_index:
      continue
    check = 0
    for i in (f, l):
      if s[i] == 0:
        check += 1
    if check <= k:
      if l-f > res:
        res = l-f

print(res)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
S = input()
lt0, lt1 = [], []
cnt0, cnt1 = 0, 0
for i in range(N):
    if i == 0:
        if S[i] == '0':
            cnt0 += 1
        else:
            cnt1 += 1
    elif S[i] == '0':
        if S[i] == S[i-1]:
            cnt0 += 1
        else:
            lt1.append(cnt1)
            cnt0 = 1
            cnt1 = 0
    elif S[i] == '1':
        if S[i] == S[i-1]:
            cnt1 += 1
        else:
            lt0.append(cnt0)
            cnt0 = 0
            cnt1 = 1
if S[N-1] == '0':
    lt0.append(cnt0)
elif S[N-1] == '1':
    lt1.append(cnt1)

n = len(lt0)
mxcnt = 0
flg = int(S[0])
if n <= K:
    mxcnt = N
else:
    for i in range(n-K+1):
        cnt = sum(lt0[i:i+K]) + sum(lt1[i:i+K+flg])
        mxcnt = max(mxcnt, cnt)

print(mxcnt)

Submission status: Wrong Answer

Solution code:
N, trial = input().split()
N, trial = int(N), int(trial)
row = input()
temp = row[0]
row = row[1:]
ppl = []
count = 1
for i in row:
  if i != temp: #切り替えの時
    ppl.append(count)
    count = 1
    temp = i
  else:
    count += 1
ppl.append(count) 
#print(ppl) #pplは人の塊のリスト
if temp == '1':
  temp = 0
  for i in range(len(ppl)):
    comp = sum(ppl[i:i+2*trial+1])
    if temp < comp:
      temp = comp
    else:
      pass
else:
  temp = 0
  for i in range(len(ppl)):
    comp = sum(ppl[i:i+2*trial])
    if temp < comp:
      temp = comp
    else:
      pass
print(temp)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().strip().split(' '))
s = input()
c = 0
d = 0
for i in range(n):
    if s[i : i + 2] == '01':
        c = c + 1
        d = i + 2
        if c == k:
            break
    elif s[i:i+1] == '1':
        d = i + 1
c = 0
e = 0
for i in range(n):
    if s[n-i-2:n-i] == '10':
        c = c + 1
        e = i + 2
        if c == k:
            break
    elif s[n-i-1:n-i] == '1':
        e = i + 1
print(max(d,e))

Submission status: Wrong Answer

Solution code:
import numpy as np

N,K = map(int, input().split())
s = list(input())
S = np.zeros(len(s)+1)
sl = []
for i in range(len(s)):
    S[i] = int(s[i])

S[len(s)] = 1 - S[len(s)-1]

#print(S)
a = 1
for i in range(1,len(s)+1):
    
    if S[i] != S[i-1]:
        
        sl.append(a)
        #print(i,a)
        a = 1
    else :
        a += 1

slm = [] 
for i in range (len(sl) - (2*K)):
    #print(i,K)
    #print(sl[0:2])
    if i == 0:
        slm.append(sum(sl[i:i+2*K]))
    else:
        slm.append(sum(sl[i:i+2*K+1]))
if len(sl) - (2*K) > 0:
    print(max(slm))
else:
    print(max(sl))

Submission status: Wrong Answer

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

is1 = False
firstIs1 = False

if S[0:1] == '1' :
    is1 = True
    firstIs1 = True

l0 = []
l1 = []
cnt = 1
isDeli = False

for i in range(0, len(S)) :
    if i == len(S) - 1 or S[i] != S[i+1] :
        if is1 == False :
            l0.append(cnt)
        else :
            l1.append(cnt)
        if i != len(S) - 1 :
            if S[i + 1] == '1' :
                is1 = True
            else :
                is1 = False
        cnt = 1
    else :
        cnt += 1

ans = 0

for i in range(min(len(l0), len(l1)) - K + 1) :
    sum = 0
    for j in range(i, i + K) :
        sum += l0[j] + l1[j]
    if i != 0 and firstIs1 == False:
        sum += l1[i - 1]
    if i != min(len(l0), len(l1)) - K - 1 and firstIs1 == True:
        sum += l1[i + 1]
    ans = max(ans, sum)

if min(len(l0), len(l1)) == 0 :
    if K > 0 or S == '1':
        ans = 1
    else :
        ans = 0


print(ans)




#print(l0)
#print(l1)

"""
for i in range(1, len(S)) :
    if isDeli = True :

        if S[i] == '0' :
            is1 = False
        else :
            is1 = True

        cnt = 1
    if S[i-1] == S[i] :
        cnt += 1
    else :
        if is1 == True :
            l1 =
"""

Submission status: Wrong Answer

Solution code:
import numpy as np

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

arr0 = np.array(list(map(len, s.split('1'))))
arr0 = arr0[arr0!=0]

arr1 = np.array(list(map(len, s.split('0'))))
arr1 = arr1[arr1!=0]

ans = 0
if s[0] == '0':
    for i in range(len(arr0)+1-k):
        if i == 0:
            length = arr0[i:i+k].sum() + arr1[i:i+k].sum()
        else:
            length = arr0[i:i+k].sum() + arr1[i-1:i+k].sum()
        ans = max(ans, length)
        
else:        
    for i in range(len(arr0)+1-k):
        length = arr0[i:i+k].sum() + arr1[i:i+k+1].sum()
        ans = max(ans, length)
        print(i, length, arr0, arr1, arr0[i:i+k], arr1[i:i+k+1])

if len(s) == s.count('1'):
    print(len(s))
else:
    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をうめる時！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:
l,k=map(int,input().split())
s=input()
import re
c=lambda i,n:[len(x.group()) for x in re.finditer(str(n)+'+',i)]
l1=c(s,1)
l0=c(s,0)
f=0
for i in range(len(l0)-k+1):
  if s[0]=='1':
    p=l1[i:i+k+1]
  else:
    p=l1[i:i+k]
  m=sum(l0[i:i+k])+sum(p)
  if f<m:f=m
print(f)

Submission status: Wrong Answer

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

def return_ans(S_initial, S):
    ans = 0
    block_size_list = []
    tmp_block_size = 1
    for i in range(1, N):
        if S[i - 1] == S[i]:
            tmp_block_size += 1

        else:
            block_size_list.append(tmp_block_size)
            tmp_block_size = 1
        if i == N - 1:
            block_size_list.append(tmp_block_size)

    if K % 2 == 1:
        if K * 2 >= len(block_size_list):
            ans = len(S)
        else:
            for i in range(len(block_size_list) - K -1):
                ans = max(ans, sum(block_size_list[i:i + K * 2]))
    else:
        block_size_list.append(0)
        if K * 2 >= len(block_size_list):
            ans = len(S)
        else:
            if S_initial == 0:
                for i in range(len(block_size_list) - K -1):
                    ans = max(ans, sum(block_size_list[i:i + K * 2 + i % 2]))

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

    return ans

print(return_ans(S[0], S))

Submission status: Wrong Answer

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

a=[]
b=[]
before="init"
for i in s:
    if before != i:
        if i == 1:
            a.append(1)
        else:
            b.append(1)
        before=i
        continue
    if before == 1:
        a[-1] += 1
    else:
        b[-1] += 1

m=0
for i in range(len(a)-k):
    tmp = sum(a[i:(i+k+1)]) + sum(b[i:(i+k)])
    if m < tmp:
        m=tmp

print(m)

Submission status: Wrong Answer

Solution code:
import sys
from itertools import accumulate
N, K  = map(int, input().split())
ans = 0
num = 0
S = input()
a = S.split('1')
b = S.split('0')
ls = []
for x in a:
    if len(x) != 0:
        ls.append(len(x))
c = [0] + list(accumulate(ls))
ls_ = []
for x in b:
    if len(x) != 0:
        ls_.append(len(x))
d = [0] + list(accumulate(ls_))

if len(c) <= K:
    print(N)
    sys.exit()

if len(c) == len(d):
    for x, y, u, t in zip(c, c[K:], d, d[K:]):
        ans = max(ans, y-x+t-u)
    print(ans)
elif len(c) == len(d)+1:
    r = d[-1]
    d.append(r)
    for x, y, u, t in zip(c, c[K:], d, d[K:]):
        ans = max(ans, y-x+t-u)
    print(ans)
elif len(c) == len(d)-1:
    q = c[-1]
    c.append(q)
    for x, y, u, t in zip(c, c[K:], d, d[K+1:]):
        ans = max(ans, y-x+t-u)
    print(ans)

Submission status: Wrong Answer

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

l=[]
if s[0]=="0":
	l.append(0)
else:
	pass

for i in range(1,n):
	if s[i-1]=="1" and s[i]=="0":
		l.append(i)
	else:
		pass
l.append(n)
ans=[]
m=len(l)
if k>=m:
	print n
else:
	for j in range(m-k-1):
		ans.append(l[j+k+1]-l[j]-1)
	print ans

	if len(ans)==0:
		print n
	else:
		print max(ans)

Submission status: Wrong Answer

Solution code:
N,K = [int(i) for i in input().split()]
S = list(map (int, list(input())))
start = S[0]
row = []
state = [0,start]
for i in S:
    if i == start:
        state[0] += 1
    else:
        row.append(state)
        start = i
        state = [1,i]
row.append(state)
print(row)
ans = []
for i in range(max(len(row)-K*2,1)):
    if row[i][1] == 1:
        ans.append(sum([row[i][0] for i in range(i,min(K*2+i+1,len(row)))]))
    else:
        ans.append(sum([row[i][0] for i in range(i,min(K*2+i,len(row)))]))
print(max(ans))

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:
                minus -= 1
                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 = map(int,input().split(" "))

person = [int(i) for i in list(input())]

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(len(person))
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))