level - medium
[문제 내용]
주어진 배열에서 0을 k만큼 1로 바꾸어 연속된 1의 최대 개수를 반환
[example 1]
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
[example 2]
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
[해결 방법]
배열의 0번째부터 시작해 하나씩 0인지 확인하여
0이면 queue에 해당 index를 저장하고
start, end 인자를 관리하여 1의 시작과 끝을 표시하고
0을 저장하는 queue의 크기가 k가 되면 하나를 뺌과 동시에
start 도 이동하며 최대 개수를 찾는다.
class Solution {
public int longestOnes(int[] nums, int k) {
int max = 0;
LinkedList<Integer> zeroes = new LinkedList<>(); // 0의 index 관리
int start = 0, end = 0; // 1의 처음과 끝을 저장할 인자
for(int i=0; i<nums.length; i++) {
if(nums[i] == 0) {
zeroes.add(i);
}
if(zeroes.size() > k) {
int count = end - start;
if(max < count) {
max = count;
}
start = zeroes.pop()+1;
}
end++;
}
int count = end-start;
if(max < count) {
max = count;
}
return max;
}
}