Given an array A of 0's and 1's, and a value K which indicates that you may change up to K values from 0 to 1. Return the length of the longest (contiguous) subarray that contains only 1’s.
Input: nums =[1,1,1,0,0,0,1,1,1,1,0], k =2Output: 6Explanation:
To obtain the longest contiguous subarray of 1s, you can flip the 0s at index 5 and 10 to 1s:[1,1,1,0,0,1,1,1,1,1,1]
Example 2:
1
2
3
Input: nums =[0,1,0,0,1,1,0,1,1,0,0,1,1], k=3Output: 9Explanation: Replace the 0s at index 6,9, and 10with1s to get the longest contiguous subarray of 1s.
We use a sliding window to keep track of the longest subarray containing only 1s, allowing up to K replacements of 0s to 1s. By expanding the window to the right and shrinking it from the left when the number of zeros exceeds K, we efficiently find the answer.
classSolution {
public:int longestOnes(vector<int>& nums, int k) {
int left =0, maxLen =0, numReplacements =0;
for (int right =0; right < nums.size(); ++right) {
if (nums[right] ==0) numReplacements++;
while (numReplacements > k) {
if (nums[left] ==0) numReplacements--;
left++;
}
maxLen = max(maxLen, right - left +1);
}
return maxLen;
}
};
classSolution {
publicintlongestOnes(int[] nums, int k) {
int left = 0, maxLen = 0, numReplacements = 0;
for (int right = 0; right < nums.length; right++) {
if (nums[right]== 0) numReplacements++;
while (numReplacements > k) {
if (nums[left]== 0) numReplacements--;
left++;
}
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funlongestOnes(nums: IntArray, k: Int): Int {
var left = 0var maxLen = 0var numReplacements = 0for (right in nums.indices) {
if (nums[right] ==0) numReplacements++while (numReplacements > k) {
if (nums[left] ==0) numReplacements-- left++ }
maxLen = maxOf(maxLen, right - left + 1)
}
return maxLen
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
deflongestOnes(self, nums: list[int], k: int) -> int:
left =0 maxLen =0 numReplacements =0for right in range(len(nums)):
if nums[right] ==0:
numReplacements +=1while numReplacements > k:
if nums[left] ==0:
numReplacements -=1 left +=1 maxLen = max(maxLen, right - left +1)
return maxLen
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnlongest_ones(nums: Vec<i32>, k: i32) -> i32 {
let (mut left, mut max_len, mut num_replacements) = (0, 0, 0);
for right in0..nums.len() {
if nums[right] ==0 { num_replacements +=1; }
while num_replacements > k {
if nums[left] ==0 { num_replacements -=1; }
left +=1;
}
max_len = max_len.max(right - left +1);
}
max_len asi32 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
longestOnes(nums: number[], k: number):number {
letleft=0, maxLen=0, numReplacements=0;
for (letright=0; right<nums.length; right++) {
if (nums[right] ===0) numReplacements++;
while (numReplacements>k) {
if (nums[left] ===0) numReplacements--;
left++;
}
maxLen= Math.max(maxLen, right-left+1);
}
returnmaxLen;
}
}