Loading content...
You are given a binary array nums consisting exclusively of 0s and 1s, along with a non-negative integer k representing your modification budget.
Your task is to determine the maximum length of a contiguous subarray containing only 1s that can be achieved by converting at most k zeros into ones.
The modification operation transforms a 0 into a 1, and you may use anywhere from zero modifications up to your full budget of k modifications. The goal is to find the longest possible run of consecutive 1s achievable within these constraints.
Note that you do not actually modify the array; you simply calculate what the longest contiguous segment of 1s would be if you were allowed to make up to k such transformations optimally.
nums = [1,1,1,0,0,0,1,1,1,1,0]
k = 26By converting the zeros at indices 5 and 10 to ones, we obtain the subarray [1,1,1,1,1,1] spanning indices 5 through 10 (inclusive), yielding a contiguous segment of length 6. This is the maximum achievable with at most 2 modifications.
nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1]
k = 310We can convert zeros at positions 4, 5, and 9 to create a contiguous segment of 1s from index 2 to index 11, giving us a maximum length of 10 consecutive ones.
nums = [1,1,1,1,1]
k = 25The entire array already consists of 1s, so no modifications are needed. The longest contiguous segment is the full array with length 5.
Constraints