이진 배열(0 또는 1로만 구성된 배열)을 유일한 인수로 사용하는 JavaScript 함수를 작성해야 합니다.
함수는 1로만 구성된 배열의 연속적인 하위 배열의 길이를 찾아 반환해야 합니다.
예를 들어 -
입력 배열이 -
인 경우const arr = [1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1];
그러면 출력은 다음과 같아야 합니다. -
const output = 4;
슬라이딩 창 알고리즘을 사용하여 1로만 구성된 가장 큰 창(크기가 가장 큰 창)을 캡처합니다.
예시
이에 대한 코드는 -
const arr = [1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1];
const findMaxConsecutiveOnes = (arr = []) => {
let left = 0;
let right = 0;
let max = 0;
while (right < arr.length) {
if (arr[right] === 0) {
if (right - left > max) {
max = right - left
};
right++;
left = right;
} else {
right++
};
};
return right - left > max ? right - left : max;
}
console.log(findMaxConsecutiveOnes(arr)); 출력
콘솔의 출력은 -
4