Problem:


Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.



Sample input:
5 1
00010


Sample output:
4

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
S = input()
group = []
people = 0
start = S[0]
now = S[0]
for i in range(N):
    if S[i] == now:
        people += 1
    else:
        group.append(people)
        people = 1
        if S[i] == "1":
            now = "1"
        else:
            now = "0"
group.append(people)
group += [0, 0, 0]
ans = 0
group
if start == "1":
    ans = sum(group[:min(len(group), 2*K+1)])
    anstemp = ans
    indexl = 0
    index = 2*K+1
    while index <= len(group):
        index += 2
        indexl += 2
        anstemp += sum(group[index-2:index])-sum(group[indexl-2:indexl])
        ans = max(ans, anstemp)
else:
    indexl = 0
    ans = sum(group[:min(len(group), 2*K)])
    anstemp = ans
    index = 2*K
    while index <= len(group):
        index += 2
        indexl += 2
        anstemp += sum(group[index-2:index]) - sum(group[indexl-2:indexl])
        ans = max(ans, anstemp)


S = S[::-1]
group = []
people = 0
start = S[0]
now = S[0]
for i in range(N):
    if S[i] == now:
        people += 1
    else:
        group.append(people)
        people = 1
        if S[i] == "1":
            now = "1"
        else:
            now = "0"
group.append(people)
group += [0, 0, 0]
group
ans2 = 0
if start == "1":
    ans2 = sum(group[:min(len(group), 2*K+1)])
    anstemp = ans2
    indexl = 0
    index = 2*K+1
    while index <= len(group):
        index += 2
        indexl += 2
        anstemp += sum(group[index-2:index])-sum(group[indexl-2:indexl])
        ans2 = max(ans2, anstemp)
else:
    indexl = 0
    ans2 = sum(group[:min(len(group), 2*K)])
    anstemp = ans2
    index = 2*K
    while index <= len(group):
        index += 2
        indexl += 2
        anstemp += sum(group[index-2:index]) - sum(group[indexl-2:indexl])
        ans2 = max(ans2, anstemp)

print(max(ans, ans2))

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
                minus -= 1
                break
            if S[left - minus] == '1':
                # 1ならまだ伸ばせる
                minus += 1
            else:
                # 0の場合はもう終わり
                minus -= 1
                break
        left -= minus
    # positionから右にk個反転させる
    if idx + K -1 >= len(positions):
        # もうみなくていい
        break
    # endはplus1idxになってる
    end = positions[idx + K-1][1]
    if end != N:
        a = 0
        while True:
            #  print(end, a)
            if end + a >= N:
                break
            if S[end + a] == '1':
                a += 1
            else:
                #0の場合
                if a != 0:
                    a -= 1
                break
        end += a

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

Submission status: Wrong Answer

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

S=[]
if S_inp[0]=='0':
  S.append(0)

dmy=1
for i in range(N-1):
  if S_inp[i]==S_inp[i+1]:
    dmy+=1
  else:
    S.append(dmy)
    dmy=1
S.append(dmy)
if len(S) % 2 ==1:
  S.append(0)

#2*K+1の長さが取れる。
if len(S)==2:
  print(max(S))
else:
  T=[]
  res=0
  for j in range(int(len(S)/2-K)):
    i=j*2
    #T.append(sum(S[i:i+2*K+1]))
    if sum(S[i:i+2*K+1]) > res:
      res = sum(S[i:i+2*K+1])
  #print(max(T))
  print(res)

Submission status: Wrong Answer

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

people = []
prev = s[0]
neg = False
if prev == "0":
	neg = True

count = 1

for i in range(1, len(s)):
	if prev != s[i]:
		people.append(count)
		count = 0
		prev = s[i]
	count += 1
people.append(count)

if len(people)/2 <= k:
	print(n)
	quit()

scan, step, start = k*2, 1, 1
if neg == False:
	scan += 1
	step, start = 2, 2

prev = 0
for j in range(scan):
	prev += people[j]
max_people = prev

for i in range(start, len(people)-scan+1, step):
	if step == 2:
		cur_sum = prev - people[i-1] - people[i-2]
		cur_sum += people[i+scan-1] + people[i+scan-2]
	else:
		cur_sum = prev - people[i-1]
		cur_sum += people[i+scan-1]
	prev = cur_sum
	max_people = max(max_people, cur_sum)

print(max_people)

Submission status: Wrong Answer

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):
        u = l
        v = l + 2 * K - 2
        if l > 0:
            u = l - 1
        if l + 2 * K - 1 < len(a):
            v = l + 2 * K - 1
        if max(a[u:v]) * (v - u + 1) < count:
            break

        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:
N, K = map(int, input().split())
S = input()

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

if S[0] == '1':
    if K >= len(change)//2:
        print(N)
        quit()
else:
    if K >= (len(change)+1)//2:
        print(N)
        quit()

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

Submission status: Wrong Answer

Solution code:
n,k=[int(i) for i in input().split()]
s=input()
tmp=""
cnt=1
for i in range(n-1):
    if s[i]==s[i+1]:
        cnt+=1
    else:
        tmp+=str(cnt)
        cnt=1
tmp+=str(cnt)
ans=0
for i in range(len(tmp)-k*k+1):
    before=sum([int(j) for j in tmp[:i]])
    Sum=sum([int(j) for j in tmp[i:i+k*k+1]])
    after=sum([int(j) for j in tmp[i+k*k+1:]])
    if Sum>ans:
        ans=Sum
        if s[before-1]=="1" and tmp[:i]!="":
            ans+=int(tmp[i-1])
        if s[after]=="1":
            try:
                ans+=int(tmp[i+k*k+1])
            except:
                pass
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 21:27:24 2019
ABC124D
@author: maezawa
"""

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

max1 = 0
ki = 0
ser1s = 0
inv01 = []
i = 0
while i < n:
    #print(i, max1, ki, ser1s)
    #print(inv01)
    if s[i] == 1:
        ser1s += 1
        i += 1
        if max1 < ser1s:
            max1 = ser1s
        continue
    else:
        if ki+1 <= k:
            ki += 1
            ser1s += 1
            for j in range(i+1,n):
                if s[j] == 0:
                    ser1s += 1
                else:
                    i = j-1
                    break
            inv01.append(i)
        else:
            if max1 < ser1s:
                max1 = ser1s
            for j in range(i+1,n):
                if s[j] == 0:
                    ser1s += 1
                else:
                    i = j-1
                    break
            inv01.append(i)
            rm = inv01.pop(0)
            ser1s = i - rm
            #ki -= 1
    i += 1

print(max1)

Submission status: Wrong Answer

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

if int(S[0]) == 0:
  intervals = []
else:
  intervals = [0]
  
interval = 0
state = int(S[0])
for s in S:
  if int(s) == state:
    interval += 1
  else:
    intervals.append(interval)
    interval = 1
    state = int(s)
if int(S[N-1]) == 0:
  intervals.append(0)
else:
  intervals.append(interval)
    
n = len(intervals)
length = sum(intervals[0:2*K])
for i in range(2, n, 2):
  if 2*K+i >= n:
    break
  length = max(length, sum(intervals[i-1:2*K+i]))
print(length)

Submission status: Wrong Answer

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

runlength_one = []
runlength_zero = []
counter = 0
prev = '1'
for s in S:
    if s == prev:
        counter += 1
    else:
        if s == '1':
            runlength_zero.append(counter)
        else:
            runlength_one.append(counter)
        counter = 1
        prev = s
if S[-1] == '1':
    runlength_one.append(counter)
else:
    runlength_zero.append(counter)


max = 0
for i in range(len(runlength_one) - K):
    length = sum(runlength_one[i:i+K+1]) + sum(runlength_zero[i:i+K])
    max = length if max < length else max

if max == 0:
    max = sum(runlength_one) + sum(runlength_zero)

print(str(max))

Submission status: Wrong Answer

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

zero_idx = []
list_ct = []
flg_1 = 0
flg_0 = 0
idx = 0
zero_ct = 0
zero = []
count = 0

if S[0] == '0':
    list_ct.append(0)

for i in S:
    if flg_1 == 0:
        if i == '1':
            if zero_ct:
                zero.append(zero_ct)
                zero_ct = 0
            flg_0 = 0
            count = 1
            flg_1 = 1
            idx += 1
        else:
            if flg_0 == 0:
                zero_ct += 1
                zero_idx.append(idx)
                flg_0 = 1
            else:
                zero_ct += 1
    else:
        if i == '1':
            count += 1
        else:
            flg_1 = 0
            flg_0 = 1
            list_ct.append(count)
            list_ct.append(0)
            if S[0] == '0':
                zero_idx.append(idx+1)
            else:
                zero_idx.append(idx)
            count = 0
            zero_ct = 1
            idx += 1

if count != 0:
    list_ct.append(count)
if S[-1] == '0':
    zero.append(zero_ct)

j = 0
for i in zero_idx:
    list_ct[i] = zero[j]
    j += 1

Max = 0
if zero_idx:
    if S[0] != '0':
        for i in range(len(zero_idx)-K+1):
            num = sum(list_ct[zero_idx[i]-1:zero_idx[i+K-1]+2])
            if num > Max:
                Max = num
    else:
        for i in range(len(zero_idx)-K+1):
            if i != 0:
                num = sum(list_ct[zero_idx[i]-1:zero_idx[i+K-1]+2])
                if num > Max:
                    Max = num
            else:
                num = sum(list_ct[zero_idx[i]:zero_idx[i+K-1]+2])
                if num > Max:
                    Max = num
else:
    Max = sum(list_ct)

print(Max)

Submission status: Wrong Answer

Solution code:
N, K = input().split()
N=int(N)
K=int(K)
list1 = []
list1 = [int(i) for i in input()]
list2 = []
for j in range(N):
    max1 = 0
    lim = 0
    for i in range(j,N):
        if list1[i]==1:
            if lim > K:
                break
            max1 += 1
        elif i!=0:
            if list1[i-1]==0:
                max1 +=1
            else:
                if lim >= K:
                    break
                lim += 1
                max1 +=1
        elif i==0:
            max1 += 1
            lim += 1
    list2.append(max1)

print(max(list2))

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))[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))[::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:
n, k = map(int,input().split())

s = input()

a = []
b = []
flag = True
count = 0
m = 0
sum_ = 0
tmp = 0
j = 0
length = 0

for i in range(len(s) - 1):
    if i == 0 and s[i] == '1':
        a.append(0)
        length += 1
        flag = False

    if flag:
        if s[i] == s[i+1]:
            count += 1
        else:
            a.append(count+1)
            length += 1
            sum_ += count+1

            if length - k * 3 >= 0:
                sum_ -= a[length-k*3]

            flag = False
            count = 0
    else:
        if s[i] == s[i+1]:
            count += 1
        else:
            a.append(count+1)
            length += 1
            sum_ += count+1

            if length - k * 3 >= 0:
                sum_ -= a[length-k*3]

            m = max(m, sum_)

            flag = True
            count = 0

a.append(count+1)
length += 1
sum_ += count+1

if length - k * 3 >= 0:
    sum_ -= a[length-k*3]

if s[-1] == '0':
    if length - k * 3 >= 0:
        sum_ -= a[length-k*3+1]
    m = max(m, sum_)
else:
    m = max(m, sum_)

print(m)

Submission status: Wrong Answer

Solution code:
N, K = map(int,input().split())
S = input()
nums = []
tmp = S[0]
init = int(tmp)
count = 0
for s in S:
    if tmp == s:
        count += 1
    else:
        nums.append(count)
        count = 1
        tmp = s

if init == 0:
    #始め0の場合
    lenmax = sum(nums[:2*K])
    #それ以外は1ことばし
    for i in range(1,len(nums)-2*K,2):
        if i + 2*K == len(nums):
            lenmax = max(lenmax,sum(nums[i:i+2*K]))
        else:
            lenmax = max(lenmax,sum(nums[i:i+2*K+1]))

elif init == 1:
    lenmax=0
    #それ以外は1ことばし
    for i in range(len(nums)-2*K,2):
        if i + 2*K == len(nums):
            lenmax = max(lenmax,sum(nums[i:i+2*K]))
        else:
            lenmax = max(lenmax,sum(nums[i:i+2*K+1]))

print(lenmax)

Submission status: Wrong Answer

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

S = input()
para = [0]
for i, s in enumerate(S):
    if i == 0:
        para.append(1)
    else:
        if S[i] == S[i-1]:
            para[-1] += 1
        else:
            para.append(1+para[-1])


i = 0

tmpmax = 0

if S[0] == '1':
    if 2*k + 1 >= len(para) - 2:
        print(n)
    else:
        while i + 2*k + 1 <= len(para) - 1:
            j = i + 2*k + 1
            if para[j] - para[i-1] > tmpmax:
                tmpmax = para[j] - para[i]

            i += 2
        print(tmpmax)
else:
    if 2*k >= len(para) - 1:
        print(n)
    else:
        while i + 2*k <= len(para) - 2:
            j = i + 2*k
            if i == 0:
                if para[j] - para[i] > tmpmax:
                    tmpmax = para[j] - para[i]
            else:
                if para[j] - para[i-1] > tmpmax:
                    tmpmax = para[j] - para[i-1]

            i += 2
        print(tmpmax)

Submission status: Wrong Answer

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

zero_positions = [0] + [i for i, c in enumerate(S) if c==0]
count0 = 0
start = 0
end = 0
numbers = 0
index = 0
load_0 = False
l_0 = False
scores = []
while True:
    if (not load_0) and S[index] == '0':
        count0 += 1
        load_0 = True
    elif load_0 == True and S[index] == '1':
        load_0 = False
    if count0 == K+1:
        scores.append(index - start)
        while count0 > K:
            if (not l_0) and S[start] == '0':
                l_0 = True
            elif l_0 == True and S[start] == '1':
                count0 -= 1
                l_0 = False
            start += 1
    index += 1
    if index == N:
        scores.append(index-start)
        break
        
print(max(scores))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
import sys
n,k = [int(i) for i in input().split()]
s=input()

a = []
c = 0
now = 1
for ss in s:
    if str(now) == ss:
        c += 1
    else:
        now = 1 - now
        a.append(c)
        c=1
a.append(c)
if now == 1:
    a.append(0)

#print(s)
#print(a)

L = len(a)
ans = sum(a[0:2*k+1])
newans=ans
right = 2*k+2
while(right < L):
#    print(right,"r",ans, a[right],  a[right-1], a[right-2*k-1],  a[right-2*k-2])
    newans += a[right] + a[right-1]- a[right-2*k-1] - a[right-2*k-2]
    right += 2
#    print(newans)
    ans = max(ans,newans)
#print("ans")
print(ans)

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.set) == 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

before_after = {}
pset = PrioritySet()
for i in range(len(zero_potentials)):
    before = None
    after = None
    if i > 0:
        before = i-1
    if i < len(zero_potentials)-1:
        after = i+1
    before_after[i] = (before, after)
    pset.add(-sum(zero_potentials[i]), i)

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

    if before is not None:
        zero_potentials[before][2] = -pri
        before_before, _ =  before_after[before]
        before_after[before] = (before_before, after)
        pset.add(-sum(zero_potentials[before]), before)
    if after is not None:
        zero_potentials[after][0] = -pri
        _, after_after =  before_after[after]
        before_after[after] = (before, after_after)
        pset.add(-sum(zero_potentials[after]), after)
    result = -pri

print(result)

Submission status: Wrong Answer

Solution code:
from sys import stdin
sN,sK = stdin.readline().rstrip().split()
N,K = int(sN), int(sK)
S = stdin.readline().rstrip()
# print(N,K)
# print(S)

k = len(S.split("1"))
# print("k:",k)
num = 0
for itr in range(0,N):
    if K < k:
        # print(S[:N-itr].split("1"))
        list1 = S[:N-itr].split("1")
        c = 0
        for itr2 in list1:
            if itr2:
                c += 1
        k = c
    else:
        num = itr
        break
ans_str = S[:N-num].replace("0","1") + S[N-num:]
# print("num:",num)
# print("ans_str:",ans_str)
ans = 0
for itr in range(0,N):
    if ans_str[itr] == "1":
        ans += 1
print("ans:",ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
S = input().split('1')
while '' in S:
    S.remove('')
if len(S) <= K:
    print(N)
else:
    ans = N
    S1 = S[0]
    del S[0]
    S2 = S[-1]
    del S[-1]
    for i in range(len(S)-K):
        if len(S1) <= len(S2):
            ans = ans - len(S1)
            S1 = S[0]
            del S[0]
        else:
            ans = ans - len(S2)
            S2 = S[-1]
            del S[-1]
    print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
c=list(input())
place=[0]
dist=[0]*n
for i in range(len(c)-1):
    if c[i]!=c[i+1]:
        place.append(i)
place.append(n-1)
for i in range(len(place)-2*k-2):
    dist[i]=place[i+2*k+2]-place[i]
print(max(dist)-1)

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):
  print("f: " + str(f))
  for l in range (last_index, n):
    print("  l: " + str(l))
    if f > l:
      continue
    check = 0
    for i in range(f, l):
      if s[i] == "0":
        check += 1
    if check <= k:
      if l-f > res:
        res = l-f +1

print(res+1)

Submission status: Wrong Answer

Solution code:
import numpy
N,K=(int(x) for x in input().split())
S=input()

def Solve(S,K):
    if S.count("0")<=K:
        return len(S)
    if S[0]=="1":
        S="0"+S
    

    LA=[]#立ってる人 = 0
    LB=[]#逆立ちしてる人 = 1
    k=-1
    current="0"
    appendLA=LA.append
    appendLB=LB.append
    for i,s in enumerate(S):
        k+=1
        if s!=current:
            if s=="0":
                appendLA(k)#逆立ちの個数 = 1
                current="0"
                k=0
            else:
                appendLB(k)#立ってる人個数 = 0
                current="1"
                k=0
                
    if current=="1":
        appendLA(k+1)
    else:
        appendLB(k+1)
        appendLA(0)
        
    mx=0



    sum_LA = list(numpy.cumsum(LA))
    sum_LB=list(numpy.cumsum(LB))
    

    for i in range(len(LA)-K+1):
        if i==0:
            result=sum_LA[K-1]+sum_LB[K-1]
        elif i==1:
            result=sum_LA[i+K-1]+sum_LB[i+K-1]-sum_LB[i-1]
        else:
            result=sum_LA[i+K-1]-sum_LA[i-2]+sum_LB[i+K-1]-sum_LB[i-1]
        mx=max(mx,result)

    return mx

print(Solve(S,K))

Submission status: Wrong Answer

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)
temp = sum(lst[0:2*K])
maximum = max(maximum, temp)
for i in range(2, l, 2):
	end = i+2*K
	maximum = max(maximum, temp - lst[i-2] + sum(lst[end-2:end]))
print(maximum)

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)):
        if i+k > len(arr0):
            break
        
        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)):
        if i+k > len(arr0):
            break
        
        
        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:
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)
h = 1 if ones[0] == 0 else 0
if (len(ones)+1)//2-h <= 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((len(ones)+1)//2+1-k):
    q = max(0,j*2-1)
    w = 0 if q == 0 else d[q-1]
    ans = max(ans, d[(j+k)*2-1]-w)
 
print(ans)

Submission status: Wrong Answer

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

L = [1]

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

n = len(L)
if S[0] == "1":
	if n // 2 <= K:
		print(N)
	else:
		if S[-1] == "1":
			x = L[0]
			for i in range(K):
				x += L[2 * i + 1] + L[2 * i + 2]
			val = x
			for i in range(int(n // 2) - K):
				val += L[2 * (i + K) + 1] + L[2 * (i + K) + 2] - L[2 * i] - L[2 * i + 1]
				if val > x:
					x = val
			print(x)
		else:
			x = L[0]
			for i in range(K):
				x += L[2 * i + 1] + L[2 * i + 2]
			val = x
			for i in range(int(n // 2) - K - 1):
				val += L[2 * (i + K) + 1] + L[2 * (i + K) + 2] - L[2 * i] - L[2 * i + 1]
				if val > x:
					x = val
			val += L[-1] - L[-2 * K - 1] - L[-2 * K - 2]
			if val > x:
				x = val
			print(x)			

else:
	if (n + 1) // 2 <= K:
		print(N)
	else:
		if S[-1] == "1":
			LL = [L[-1 - i] for i in range(n)]
			x = LL[0]
			for i in range(K):
				x += LL[2 * i + 1] + LL[2 * i + 2]
			val = x
			for i in range(int(n // 2) - K - 1):
				val += LL[2 * (i + K) + 1] + LL[2 * (i + K) + 2] - LL[2 * i] - LL[2 * i + 1]
				if val > x:
					x = val
			print(x)

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):
    if S[0] == '0':
        q = c[-1]
        c.append(q)
        r = d[-1]
        d.append(r)
        for x, y, u, t in zip(c, c[K:], d, d[K+1:]):
            ans = max(ans, y-x+t-u)
        print(ans)
    elif S[0] == '1':
        q = c[-1]
        c.append(q)
        r = d[-1]
        d.append(r)
        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)
    q = c[-1]
    c.append(q)
    for x, y, u, t in zip(c, c[K+1:], d, d[K:]):
        ans = max(ans, y-x+t-u)
    print(ans)
elif len(c) == len(d)-1:
    r = d[-1]
    d.append(r)
    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 = list(map(int, input().split()))
s = input()
begin = s[0]
l = [begin,0]
cur = 1
for i in range(len(s)):
    if s[i] == begin:
        l[cur]+=1
    else:
        if begin == '0':
            begin = '1'
        else: begin = '0'
        l.append(begin)
        l.append(1)
        cur+=2
max = 0
for i in range(1,len(l),2):
    sumall = 0
    if l[i-1] == '0':
        if (i+k*2*2 <= len(l)):
            for j in range (k*2):
                tmp = i+j*2
                sumall+=l[tmp]
            if sumall > max: max = sumall
    else:
        if (i+(k*2+1)*2 <= len(l)):
            for j in range (k*2+1):
                tmp = i+j*2
                sumall+=l[tmp]
            if sumall > max: max = sumall+1
print (max)