#K40502. Longest Contiguous Ones After Flips
Longest Contiguous Ones After Flips
Longest Contiguous Ones After Flips
Given a binary string S
and an integer K
, your task is to determine the maximum length of a contiguous substring consisting entirely of '1's that can be obtained by flipping at most K
characters (i.e. changing '0' to '1').
You can think of the problem as finding the longest window [i, j] in the string such that the number of '0's in that window does not exceed K
. Formally, you need to maximize the length
$$L = j - i + 1,$$
subject to
$$\sum_{t=i}^{j} \mathbf{1}_{\{S[t]=='0'\}} \le K.$$
Note that the length of the string, N
, is implicitly given by len(S)
.
inputFormat
The input is read from standard input (stdin) and consists of two lines:
- The first line contains the binary string
S
(a sequence of characters, each either '0' or '1'). - The second line contains an integer
K
representing the maximum number of flips allowed.
outputFormat
Output to standard output (stdout) a single integer representing the maximum length of a contiguous substring of '1's achievable after at most K
flips.
1101001100
2
5
</p>