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

if len(s) == s.count('1'):
    print(len(s))
else:
    print(ans)

Submission status: Wrong Answer

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

now = "0"
nl = []
for i, s in enumerate(S):
    if s != now:
        now = s
        nl.append(i)

nl_even = nl[0::2]
nl_odd = nl[1::2]
if s[-1] == "1":
    nl_odd.append(len(S))
if s[0] == "0":
    nl_odd.insert(0, 0)
if len(nl_odd)>1:
    x = nl_odd[1]
else:
    x = len(S)
for i in range(len(nl_even)-k):
    x_ = nl_odd[i+k] - nl_even[i]
    x = max(x, x_)

print(x)

Submission status: Wrong Answer

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

s2 = s.replace("01","0,1").replace("10","1,0").split(",")

if s[0]== "1":
  patterns = list(map(len, s2))
else:
  patterns = [0] + list(map(len, s2))

max_len = 1

#偶数番目が１の人たち
if len(patterns) <= 2 * k + 1:
  print(len(s))
else:
  for i in range(2*k+1 , len(patterns) + 1, 2):
    length = sum(patterns[i-2*k-1 : i])
    #print(i, length)
    if length >= max_len:
      max_len = length

  print(max_len)

Submission status: Wrong Answer

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

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

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

# 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):
	if b[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:
# -*- coding: utf-8 -*-

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

number_list = []
num = 1

for i in range(N):
    if i == N - 1:
        number_list.append(num)
    else:
        if S[i] == S[i + 1]:
            num += 1
        else:
            number_list.append(num)
            num = 1

ruiseki = [number_list[0]]
for i in range(1, len(number_list)):
    ruiseki.append(ruiseki[i - 1] + number_list[i])


max_num = 0
if S[0] == '0':
    if K * 2 <= len(number_list):
        max_num = ruiseki[2 * K - 1]
    else:
        max_num = ruiseki[-1]
if S[0] == '1':
    for i in range(0, len(number_list), 2):
        if i + K * 2 > len(ruiseki) - 1:
            break
        if i == 0:
            max_num = ruiseki[i + K - 1]
        else:
            buff = ruiseki[i + K * 2] - ruiseki[i - 1]
            if buff > max_num:
                max_num = buff

if max_num == 0:
    max_num = ruiseki[0]

print (max_num)

Submission status: Wrong Answer

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

y = '2'
tmp = [0]
ans = [0]

for x in S+'2':
    if x == y:
        tmp[-1] += 1
    else:
        if K*2+1 >= min(sum(tmp), len(tmp)+1):
            pass
        elif K*2-1 >= sum(tmp[1:-1]):
            ans.append(max(sum(tmp[1:]), sum(tmp[:-1])))
        else:
            ans.append(sum(tmp))

        y = x
        if 2*K+1 > len(tmp):
            tmp.append(1)
        else:
            tmp = tmp[1:] + [1]

print(max(ans))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
AtCoder
"""
def encode(S):
    code=[]
    code.append([int(S[0]),1])
    for s in S[1:]:
        if int(s)==code[-1][0]:
            code[-1][1]+=1
        else:
            code.append([int(s),1])
    return code

def main():
    N, K=list(map(int,input().split()))
    S=list(map(str,input().split()))[0]

    E=encode(S)

    L=[]
    if E[0][0]==0:
        L.append(0)
    for s in E:
        if s[0]==1:
            L.append(s[1])
            if(len(L)<K):
                Pre=len(L)-1
            else:
                Pre=K
            for p in range(Pre):
                if 2+p>len(L):
                    continue
                L[-2-p]+=s[1]
        else:
            if(len(L)<K):
                Pre=len(L)-1
            else:
                Pre=K
            for p in range(Pre):
                if 1+p>len(L):
                    continue
                L[-1-p]+=s[1]
        # print(L)

    print(max(L))
            

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# ハノイの塔的な感じで、変換して『連続する』1をいくつまで増やせるか。順番は可換。
# 組み合わせは NC2 * K 回ある。多そう。

N, K = (int(i) for i in input().split())
S = input() # strにしてある

# 1.連続する1の数を数える関数が必要
# 2.変換の機構が必要
# 3.総当りする？
# 0があるところだけに絞ってもいい


# 1.連続する1の数を数える関数
def count_1(string):
  length = len(string)
  num = 0
  num_max = 0
  for i in range(length):
    if string[i] == '1':
      num += 1
      num_max = max(num_max, num)
    else:
      num =0
  return num_max


# 2.変換の機構
def change(string, l, r):
  hoge = str()
  for i in range(l, r):
    hoge += str( abs( int(string[i])-1 ) )
  return string[:l] + hoge + string[r:]
  



# 3.総当りする？

num = count_1(S)

for i in range(N):
  for j in range(i,N):
    num = max(num, count_1(change(S, i, j)))



print(num)

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 = -1
  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 != -1 ):
    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):
  before = max
  group_list, max = join(group_list)
  if ( before == max ):
    break

print(max)

Submission status: Wrong Answer

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

now = "0"
nl = []
for i, s in enumerate(S):
    if s != now:
        now = s
        nl.append(i)

nl_even = nl[0::2]
nl_odd = nl[1::2]
if s[-1] == "1":
    nl_odd.append(len(S))
if s[0] == "0":
    nl_odd.insert(0, 0)
if len(nl_odd)>1:
    x = nl_odd[1]
else:
    x = len(S)
print(nl_even)
print(nl_odd)
for i in range(len(nl_even)-k):
    x_ = nl_odd[i+k] - nl_even[i]
    x = max(x, x_)

print(x)

Submission status: Wrong Answer

Solution code:
from itertools import groupby
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def ii(): return int(stdin.readline())
def li(): return map(int, stdin.readline().split())
N, K = tuple(li())
S = stdin.readline() + "2"
# use window
l, r = 0, 0
cnt = 0
r_iter = groupby(S)
l_iter = groupby(S)
r_next = next(r_iter)
l_next = next(l_iter)
while r_next[0] != "2":
    # print(l, r)
    if r_next[0] == '1' and K >= 0:
        r += len(list(r_next[1]))
        r_next = next(r_iter)
        cnt = max(cnt, r - l)
        K -= 1
        continue
    elif K >=0:
        if r_next[0] == "0":
            pass
        r += len(list(r_next[1]))
        r_next = next(r_iter)
        continue
    if l_next[0] == "0":
        K += 1
    elif l_next[0] == "1":
        pass
    l += len(list(l_next[1]))
    l_next = next(l_iter)
cnt = max(cnt, r-l)
print(cnt)

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-2*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-2*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:
import sys
N, K = map(int,input().split())
if N <= 2:
    print(N)
    sys.exit()
S = input()
ans = 0
# 0か1の連続する文字数のリストを作る
ll = []
temp = 1
for i in range(1,N):
    if S[i-1] == S[i]:
        temp += 1
    else:
        ll.append(temp)
        temp = 1
    if i == N -1:
        ll.append(temp)
if len(ll) <= 2 * K:
    print(N)
    sys.exit()
# 累積和を作って高速化する
#print(ll)
l2 = [0] * len(ll)
for j in range(len(ll)):
    l2[j] = l2[j-1] + ll[j]
#print(l2)
# 先頭がゼロ→奇数番目がゼロ→どこかのゼロ（奇数番目）から始まって連続する2*K個の数の和の最大値
if S[0] == '0':
    ans = max(l2[:K*2])
    for i in range(len(ll)-(K*2))[1::2]:
        ans = max(ans,l2[min(len(l2)-1,i+(K*2+1))]-l2[i])
# 先頭が１→偶数番目がゼロ→どこかの１（奇数番目）から始まって連続する2*K+1個の数の和の最大値
else:
    for i in range(len(ll)-(K*2))[::2]:
        ans = max(ans,l2[min(len(l2)-1,i+(K*2+1))]-l2[i])
    if S[-1] == '1':
        ans = max(ans, l2[-1]-l2[-(2*K+2)])
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from copy import deepcopy


def add(queue, k, a):
    for i in range(len(queue)):
        queue[i][k] += a


n, k = map(int, input().split())
t = input()
flag = False
q = deque()
ans = []
for i in range(n):
    q.append([0, k])
    if t[i] == '1':
        add(q, 0, 1)
        flag = False
    elif not flag:
        flag = True
        p = deepcopy(q)
        for j in range(len(q)):
            if q[j][1] == 0:
                ans.append(p.popleft()[0])
        q = p
        add(q, 0, 1)
        add(q, 1, -1)
    else:
        add(q, 0, 1)
ans += [x[0] for x in q]
print(max(ans))

Submission status: Wrong Answer

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

zeros = []
num_zeros = 0
start = 0
cont = False
for i in range(N):
    s = int(S[i])
    if s == 0 and not cont:
        start = i
        cont = True
        num_zeros += 1
        zeros.append([start,1])
        continue

    elif s == 0 and cont:
        zeros[num_zeros-1][1] += 1
        continue

    elif s == 1:
        cont = False

max_length = 0
search_num = len(zeros) - K + 1
if search_num == 0:
    if S[0] == "1":
        max_length = 1
else:
    for i in range(search_num):
        S_ = S
        for k in range(K):
            zero = zeros[i+k]
            S_ = S_[:zero[0]] + '1' * zero[1] + S_[zero[0]+zero[1]:]

        sub_max_length = 0
        sub_sub_max_length = 0
        for j in range(len(S_)):
            s = int(S_[j])
            if s == 1:
                sub_sub_max_length += 1
            elif s == 0:
                if sub_max_length < sub_sub_max_length:
                    sub_max_length = sub_sub_max_length
                sub_sub_max_length = 0
            if j == len(S_)-1:
                if sub_max_length < sub_sub_max_length:
                    sub_max_length = sub_sub_max_length

        if max_length < sub_max_length:
            max_length = sub_max_length
print(max_length)

Submission status: Wrong Answer

Solution code:
import re

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

zero_ind = [m.start() for m in re.finditer('0+', S)]
one_ind = [m.start() for m in re.finditer('1+', S)]

lz = len(zero_ind)

if lz <= K:
    print(N)
else:
    if zero_ind[0] != 0:
        zero_ind = [0] + zero_ind
    else:
        one_ind = [0] + one_ind

    count = 0

    for k in range(lz - K):
        count = max(count, zero_ind[k+K] - one_ind[k])
        
    if S[-1] == "0":
        count = max(count, N - one_ind[-K])
    else:
        count = max(count, N - one_ind[-K-1])
    
    print(count)

Submission status: Wrong Answer

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

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

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

ones.append(a)
'''
if (len(ones)+1)//2 <= k:
    print(sum(ones))
    exit()
'''
ssu = 0
d = []
for u in ones:
    ssu += u
    d.append(ssu)
d.append(0)

ans = 0
for j in range(max((len(ones)+1)//2+1-k,1)):
    q = max(0,j*2-1)
    w = 0 if q == 0 else d[q-1]
    ans = max(ans, d[min((j+k)*2-1,len(d)-1)]-w)

print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import math

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

S_list = list(S)
ans_sub = []

if S_list[0] == "0":
    ans_sub.append(0)#直立
else:
    ans_sub.append(1)#逆立ち

num = 0
for i in range(1,N):
    num += 1
    if i != N-1:
        if S_list[i-1] != S_list[i]:
            ans_sub.append(num)
            num = 0
    elif i == N-1:
        if S_list[i-1] != S_list[i]:
            ans_sub.append(num)
            ans_sub.append(1)
        else:
            ans_sub.append(num+1)

max_num = 0
if ans_sub[0] == 0:
    if math.ceil((len(ans_sub)-1)/2) <= K:
        print(len(S_list))

    else:
        for i in range(1,len(ans_sub) - K):
            a =2
            


    
elif ans_sub[0] == 1:
    if math.floor((len(ans_sub)-1)/2) <= K:
        print(len(S_list))

Submission status: Wrong Answer

Solution code:
from sys import stdin
import math
import itertools


def makeIntMatrix(lines):
    intMatrix = []
    for a in makeStringMatrix(lines):
        intMatrix.append([int(b) for b in a])
    return intMatrix
 
 
def makeStringMatrix(lines):
    stringMatrix = [line.split() for line in lines]
    return stringMatrix
 
 
def makeInt(line):
    return int(line.rstrip())
 
 
def makeMultiInteger(line):
    return [int(x) for x in line.rstrip().split()]


def solve(input_string):
    K = int(input_string[0].split()[1])
    #print(K)
    l = [int(x) for x in list(input_string[1].rstrip())]
    #print(l)
    #print(cal_max_s(l))
    if len(l) == 1: return 1
    max_s_c = 0
    while(K > 0):
        s_c = 0
        for i in range(len(l)):
            s_c_h = 0
            if i == 0:
                s_c += 1
            elif l[i] == l[i-1]:
                s_c += 1
            else:
                if s_c > max_s_c:
                    max_s_c_h = s_c_h
                    max_s_c_t = i
                    for j in range(max_s_c_h, max_s_c_t):
                        l[j] = l[i]
                    # max計算
                    max_s_c = cal_max_s(l)
                else:
                    s_c_h = i
                if K > 0:
                    K -= 1
                    break
                s_c = 0
        #print(s_c)
        if s_c == len(l):
            max_s_c = s_c
            break
        #print(l)
    return max_s_c


def cal_max_s(l):
    max_s = 0
    tmp_s = 0
    if len(l) == 1: return 1
    for i in range(len(l)):
        if l[i] == 1:
            tmp_s += 1
        else:
            if tmp_s > max_s:
                max_s = tmp_s
            tmp_s = 0
    return max_s

def main():
    input_lines = stdin.readlines()
    answer = solve(input_lines)
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from statistics import mean, median,variance,stdev
import numpy as np
import sys
import math
import fractions
import itertools
import copy
import collections
from operator import itemgetter
#以下てんぷら
def j(q):
    if q==1: print("Yay!")
    else:print(":(")
    exit(0)


def ct(x,y):
    if (x>y):print("+")
    elif (x<y): print("-")
    else: print("?")

def ip():
    return int(input())
def printrow(a):
    for i in range(len(a)):
        print(a[i])
def combinations(n,r):
    if n<r:return 0
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def permutations(n,r):
    if n<r:return 0
    return math.factorial(n) // math.factorial(n - r)
#n = ip()                                     #入力整数1つ
n,k= (int(i) for i in input().split())       #入力整数横2つ以上
#a = [int(i) for i in input().split()]        #入力整数配列
a = input()                                  #入力文字列
#a = input().split()                          #入力文字配列
#n = ip()                      #入力セット(整数改行あり)(1/2)
#a=[ip() for i in range(n)]    #入力セット(整数改行あり)(2/2)
#jの変数はしようできないので注意
#全足しにsum変数使用はsum関数使用できないので注意
#こっから本文
if n==1:
    print(1)
    exit(0)
inv = [-1]
leftborder = []
rightborder= []
leftborder.append(0)
cg =[0]
if a[0]=='0':
    rightborder.append(0)
for i in range(n):
    if a[i] != a[i-1]:cg.append(i)
    if i != n-1:
        if a[i] == '0' and a[i+1] == '1': leftborder.append(i+1)
        if a[i] == '1' and a[i + 1] == '0': rightborder.append(i)
rightborder.append(n-1)
if a[n-1] == '0':
    leftborder.append(n-1)
cg.append(n-1)
#print(leftborder)
#print(rightborder)
m = 0
for i in range(len(leftborder)-k):
    m = max(rightborder[i+k]-leftborder[i]+1,m)
print(m)

Submission status: Wrong Answer

Solution code:
# coding: utf-8

import sys

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

zero_array = []
one_array = []
curr_num = ss[0]
flag = 0

if curr_num == 0:
    zero_array.append(0)
else:
    one_array.append(0)
    flag = 1

for i in ss:
    if curr_num == i:
        if i == 0:
            zero_array[-1] += 1
        else:
            one_array[-1] += 1
    else:
        curr_num = i
        if i == 0:
            zero_array.append(1)
        else:
            one_array.append(1)

# print("zero_array", zero_array)
# print("one_array", one_array)
# print("flag", flag)

if k >= len(zero_array):
    print(sum(zero_array) + sum(one_array))
    sys.exit()
else:
    t = 0
    tmp = sum(zero_array[t: t+k]) + sum(one_array[t: t+k+flag])
    max_count = tmp
    # print("outer_tmp", tmp)
    # print()
    while t + k + flag <= len(one_array) and t + k < len(zero_array):
        # print("t", t)
        tmp += zero_array[t+k] - zero_array[t]
        if t+k+flag < len(one_array):
            tmp += one_array[t+k+flag]
            if not (t == 0 and flag == 0):
                if t == 0:
                    print("yeh")
                tmp -= one_array[t+flag-1]
        elif not (t == 0 and flag == 0):
            tmp -= one_array[t+flag-1]
        # print("tmp", tmp)
        if tmp > max_count:
            max_count = tmp
            # print(t, max_count)
        t += 1

    print(max_count)
# print(zero_array)
# print(one_array)

Submission status: Wrong Answer

Solution code:
import sys
N, K = map(int, input().split())
S = sys.stdin.readline()
S = S[:-1]
check = S[0]
if check == '0':
    Slist = [0]
else:
    Slist = [1]

for i in range(len(S)-1):
    if S[i+1] == check:
        Slist[-1] += 1
    else:
        Slist.append(1)
        check = S[i+1]

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

Solution code:

def get_input():
    N,K = [int(_) for _ in input().split()]
    S = [int(_) for _  in list(input())]
    return N,K,S

def solve(N,K,S):
    length = len(S)
    array = count_array(S)
    start_char = S[0]
    ans = find_max(array,K,start_char)
    return ans

def find_max(array,K,start_char):
    if start_char ==0 and len(array) <= 2 * K:
        return sum(array)
    elif start_char == 1 and len(array) <=2 * K+1 :
        return sum(array)
    else:
        if start_char == 0:
            start,end = 1,2*K+2
        else:
            start,end = 0,2*K+1
        ret = []
        idx = 0
        current_sum = sum(array[start:end])
        while(1):
            start+=2
            end+=2
            if end > len(array):
                break
            current_sum = current_sum- sum(array[start-2:start]) + sum(array[end-2:end])
            ret.append(current_sum)
        if len(ret) == 0:
            ret.append(current_sum)
    return max(ret)
            

def count_array(S):
    array = []
    cur_char = S[0]
    cur_val = 1
    for char in S[1:]:
        if cur_char != char:
            array.append(cur_val)
            cur_char = char
            cur_val = 1
        else:
            cur_val+=1
    array.append(cur_val)

    return array





if __name__ == "__main__":
    N,K,S = get_input()
    ans = solve(N,K,S)
    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 = []
b = []
c = s[0]
num = 1
for i in range(1,n):
	if c == s[i]:
		num += 1
	else:
		a.append(num)
		b.append(c)
		num = 1
		c = s[i]
a.append(num)
b.append(c)

# 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):
	if b[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:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
input = sys.stdin.readline

# bisect_left(lists, 3)
# bisect_right(lists, 3)

def main():
	N, K = map(int, input().split(" "))
	SS = input()
	SS_org = SS.rstrip("\n")
	S = SS.rstrip("\n")
	
	S_tmp = S.split("1")

	S2_tmp = S.split("0")

	if len(S_tmp) <= K:
		print(N)
		sys.exit()
	
	ans_tmp = 0
	for i in range(K):
		ans_tmp += len(S_tmp[i])

	print(S_tmp)
	print(S2_tmp)

	
	
if __name__ == "__main__":
	main()

Submission status: Wrong Answer

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

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

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

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

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
n, k = map(int,input().split())
s = input()
a = []
i = 0
cnt = 0
now = s[0]
while i < n:
    if s[i] == now:
        cnt += 1
    else:
        a.append(cnt)
        now = s[i]
        cnt = 1
    if i == n-1:
        a.append(cnt)
    i += 1

if len(a) == 1 and s[0] == '1':
    print(n)
    exit()

if s[0] == '0':
    a = [0] + a
    n += 1
if s[-1] == '0':
    a.append(0)
    n += 1
    
r = list(accumulate(a))
lr = len(r)
ans = -float('inf')
kk = 2*k+1
for i in range(k*2, lr+1 , 2):
    if i == k*2:
        ans = max(ans, r[i])
    else:
        ans = max(ans, r[i] - r[i - kk])
print(ans)

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]
            if st == en:
                tmp += X[en + 1][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:
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)-1 <= 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(i) for i in input().split()]
S = input()
l = []
ln = 0
mae = "0"
i,ren = 0,0

if S[N-1]=="0" : S += "1"
else : S += "0"

while i<=N:
  if S[i] != mae :
    l.append(ren)
    mae = S[i]
    ren = 1
    ln += 1
  else :
    ren += 1
  i += 1

i=0
max = 0
while i<=ln-K*2-1:
  sm = sum(l[i:i+K*2+1])+1
  if max > sm : max = sm
  i+=2  

if max==0 : print(N)
else : print(max)

Submission status: Wrong Answer

Solution code:
def kakaka():
    a = list(map(int, input().split()))
    b = map(int, input().split())
    c = int(input())

def start_process():
    return
def main():
    all_num, inst_num = map(int, input().split())
    data = list(input())

    data_la = []
    ans_0, ans_1 = 0, 0
    for i in range(all_num):
        if data[i] == '1':
            ans_1 += 1
            if ans_0 > 0:
                data_la.append(ans_0)
                ans_0 = 0
        else:
            ans_0 += 1
            if ans_1 > 0:
                data_la.append(ans_1)
                ans_1 = 0
    if ans_1 > 0:
        data_la.append(ans_1)
    elif ans_0 > 0:
        data_la.append(ans_0)

    ans = 0
    ans_data = 0
    count_0 = 0
    if data[0] == '0':
        flg = 0
    else:
        flg= 1

    # print(data_la)

    if len(data_la) <= 2:
        print(sum(data_la))
    else:
        pre_data1, pre_data2 = data_la[0], data_la[1]
        pre_data1_ind, pre_data2_ind = 0, 1
        # print(data_la)
        for i in range(len(data_la)):
            if i % 2 == flg:
                count_0 += 1
            if count_0 == inst_num + 1:
                ans = ans - pre_data1 - pre_data2
                pre_data1_ind += 2
                pre_data2_ind += 2
                if pre_data1_ind >= len(data_la):
                    pre_data1 = 0
                else:
                    pre_data1 = data_la[pre_data1_ind]
                if pre_data2_ind >= len(data_la):
                    pre_data2 = 0
                else:
                    pre_data2 = data_la[pre_data1_ind]

                count_0 -= 1
            ans += data_la[i]
            # print(ans)
            if ans_data < ans:
                ans_data = ans






        print(ans_data)






if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
import re

def longest(s):
	match = re.finditer(r'1+',s)
	maxlen=0
	pos=-1
	for m in match:
		if maxlen < len(m.group(0)):
			maxlen=len(m.group(0))
			pos=m.start(0)
	return maxlen

def do_flip(s,l,r):
	substr=s[l:r]
	substr.replace('0','o').replace('1','0').replace('o','1')
	return s[:l-1] + substr + s[r+1:]

def do_cycle(niter,s):
	match = re.finditer(r'(0+|1+)',s)
	lengths=[]
	lengths.append(longest(s))
	for m in match:
		x0=m.start(0)
		x1=m.end(0)
		stmp=do_flip(s,x0,x1)
		lengths.append(longest(stmp))
		if niter > 1:
			lengths.append(do_cycle(niter-1,stmp))
	return max(lengths)

tmp=input().split(' ')
n=int(tmp[0])
k=int(tmp[1])
s=input()
nzeros=s.count('0')
if k > nzeros:
	k=nzeros
maxlen=do_cycle(k,s)
print(maxlen)

Submission status: Wrong Answer

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

Solution code:
# yield count
def aggregate(S):
  prev = S[0]
  count = 0
  for i in S:
    if i != prev:
      prev = i
      yield count
      count = 0
    count += 1
  if count != 0:
    yield count
  return

# yield count
def find_max(S, K):
  counts = list(aggregate(S))
  if len(counts) <= K*2:
    yield sum(counts)
    return
  s = 0
  e = K*2+1
  yield sum(counts[s:e])
  if S[0] == '0':
    s += 1
    e += 1
  for i in range(2, len(counts)-e+1, 2):
    yield sum(counts[i+s:i+e])

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