LeetCode [JS] > 1004. Max Consecutive Ones III

2025. 5. 5. 20:14·🔒Algorithm

📌문제링크

https://leetcode.com/problems/max-consecutive-ones-iii/description/?envType=study-plan-v2&envId=leetcode-75

📌문제풀이

이 문제는 sliding window로 접근해서 풀면된다. 시간 복잡도는 O(n) 이며 right를 1씩 증가하면서 zeroCnt 가 > k 이면 zeroCnt가 k를 넘지 않을때까지 left를 이동한뒤 right-left+1을 이용하여 1의 갯수를 구할 수 있다. 

// time complexity O(n)
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var longestOnes = function (nums, k) {
    let left = 0;
    let zeroCnt = 0;
    let max = 0;
    for (let right = 0; right < nums.length; ++right) {
        if (nums[right] === 0) {
            ++zeroCnt;
        }

        if (zeroCnt > k) {
            while (nums[left] !== 0) {
                ++left;
            }
            ++left;
            --zeroCnt;
        }

        let cnt = right - left + 1;
        max = Math.max(cnt, max);
    }
    return max;
};

'🔒Algorithm' 카테고리의 다른 글

LeetCode[JS] > 350. Intersection of Two Arrays II  (0) 2025.04.16
LeetCode[JS] > 1913. Maximum Product Difference Between Two Pairs  (0) 2025.04.09
LeetCode [JS] > 1496. Path Crossing  (0) 2025.04.08
LeetCode [JS] > 1128. Number of Equivalent Domino Pairs  (0) 2025.04.07
LeetCode [JS] > 859. Buddy strings  (0) 2025.04.05
'🔒Algorithm' 카테고리의 다른 글
  • LeetCode[JS] > 350. Intersection of Two Arrays II
  • LeetCode[JS] > 1913. Maximum Product Difference Between Two Pairs
  • LeetCode [JS] > 1496. Path Crossing
  • LeetCode [JS] > 1128. Number of Equivalent Domino Pairs
devWarrior
devWarrior
  • devWarrior
    devWarrior
    devWarrior
  • 전체
    오늘
    어제
    • 🧩Dev (263)
      • ⭐FE (34)
      • 🔒Algorithm (155)
      • ➕Etc. (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    BFS
    Lv2
    프로그래머스
    구현
    실버2
    nodejs
    Easy
    react
    자바스크립트
    leetcode
    코딩테스트
    그리디
    코테
    dp
    자스
    골드5
    프론트엔드
    FE
    javascript
    오블완
    실버4
    티스토리챌린지
    js
    Algorithm
    node.js
    실버1
    실버3
    알고리즘
    DFS
    백준
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
devWarrior
LeetCode [JS] > 1004. Max Consecutive Ones III
상단으로

티스토리툴바