Problem Description
Description
985 has a 0-1 string of length n. It is known that he can modify it at most k times (each modification flips one character, i.e. 0->1 or 1->0). He wants to know the maximum length of a contiguous all-1 substring he can obtain.
Input
The first line contains an integer t, representing t test cases.
The first line of each test case contains two integers n and k, representing the above information.
Note: 1 <= t <= 12, 1 <= n <= 100000, 0 <= k <= 100000.
Output
An integer representing the maximum length that can be obtained.
Sample Input
| |
Sample Output
| |
Problem Analysis
Yu Shen:
Solution 1: Observe that the final answer is linear, so we use Binary Search on the Answer and turn the problem into a decision problem.
For the current binary-search value mid, check its validity: whether there exists a contiguous segment of length mid such that the total number of 0 characters in that segment is <= k.
Time complexity: O(T * n * log(n)).
Solution 2: Consider dp, where dp[i] represents the optimal contiguous segment starting at the i-th character.
Then we only need to find the largest j (i <= j <= n) such that the total number of 0 characters in [i, j] is <= k.
We can first compute the Prefix Sum of 0 characters, and then binary search each time. The final answer is max(dp[i]) (1 <= i <= n).
Time complexity: O(T * n * log(n)).
Noob:
Record how many 0s there are between 0 and i and store it in cnt[i]
Then the interval [n, m] contains a[m] - a[n-1] zeros
The length (number of characters) is n-m+1
So compare k with a[m] - a[n-1] to perform interval updates
and record the maximum length seen as the result
| |
Problem link: [1895]985’s 0-1 String Problem