[LeetCode] 1493. Longest Subarray of 1's After Deleting One Element 해설 및 풀이 (Python)

2025. 4. 9. 23:04·Study/코딩 테스트
반응형

LeetCode 1493. Longest Subarray of 1's After Deleting One Element

https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/description/?envType=study-plan-v2&envId=leetcode-75


Given a binary array nums, you should delete one element from it.

Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.

 

Example 1:

Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:

Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:

Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.
 

Constraints:

1 <= nums.length <= 105
nums[i] is either 0 or 1.

 

한글 해석

 

더보기

이진 배열이 주어지면 nums, 그 중 하나의 요소를 삭제해야 합니다.

결과 배열에 ' 만 포함된 가장 긴 비어 있지 않은 하위 배열의 크기를 반환합니다 . 해당 하위 배열이 없으면 반환합니다.10

 

예시 1:

입력: nums = [1,1,0,1]
 출력: 3
 설명: 위치 2의 숫자를 삭제한 후 [1,1,1]에는 1의 값을 갖는 숫자 3개가 포함됩니다.
예 2:

입력: nums = [0,1,1,1,0,1,1,0,1]
 출력: 5
 설명: 4번째 위치의 숫자를 삭제한 후, 1의 값을 가지는 가장 긴 부분 배열 [0,1,1,1,1,0,1]은 [1,1,1,1,1]입니다.
예시 3:

입력: nums = [1,1,1]
 출력: 2
 설명: 하나의 요소를 삭제해야 합니다.
 

제약 조건:

1 <= nums.length <= 105
nums[i]0또는 둘 중 하나 입니다 1.

 


문제 유형

배열

동적 프로그래밍

슬라이딩 윈도우

 

풀이 방법 도출

 

이 문제를 해결하기 위해서 슬라이딩 윈도우를 사용하여 풀 수 있습니다.

  1. 0은 최대 1개만 제거할 수 있습니다.
  2. 윈도우 내 0의 개수가 2개 이상이 된다면 왼쪽 포인터를 이동시켜 조건을 만족시킵니다.
  3. 윈도우 크기는 right - left
  4. 0 하나를 삭제하는 조건이므로 현재 구간의 길이에서 1을 뺀 것처럼 동작합니다.

 

 

시간 복잡도

  • O(N)

핵심 코드 삽입 및 설명
class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        left = 0  # 왼쪽 포인터
        max_length = 0  # 결과값
        zero_count = 0  # 현재 윈도우 내 0의 개수
        
        for right in range(len(nums)):
            # 오른쪽 포인터를 이동하면서 0의 개수 세기
            if nums[right] == 0:
                zero_count += 1
            
            # 윈도우 내 0이 2개 이상일 경우 왼쪽 포인터 이동
            while zero_count > 1:
                if nums[left] == 0:
                    zero_count -= 1
                left += 1
            
            # 최대 길이 갱신
            max_length = max(max_length, right - left)
        
        return max_length
반응형
저작자표시 비영리 변경금지 (새창열림)

'Study > 코딩 테스트' 카테고리의 다른 글

[99클럽 코테 스터디 10일차 TIL] LeetCode 2283. Check if Number Has Equal Digit Count and Digit Value 해설 및 풀이 (Java)  (0) 2025.04.09
[프로그래머스] Lv.1 같은 숫자는 싫어 해설 및 풀이 (Python)  (0) 2025.04.09
[LeetCode] 11. Container With Most Water 해설 및 풀이 (Python)  (0) 2025.04.08
[LeetCode] 1004. Max Consecutive Ones III 해설 및 풀이 (Python)  (0) 2025.04.08
[99클럽 코테 스터디 9일차 TIL] 백준 3986번 좋은 단어 해설 및 풀이 (Java, Python)  (0) 2025.04.08
'Study/코딩 테스트' 카테고리의 다른 글
  • [99클럽 코테 스터디 10일차 TIL] LeetCode 2283. Check if Number Has Equal Digit Count and Digit Value 해설 및 풀이 (Java)
  • [프로그래머스] Lv.1 같은 숫자는 싫어 해설 및 풀이 (Python)
  • [LeetCode] 11. Container With Most Water 해설 및 풀이 (Python)
  • [LeetCode] 1004. Max Consecutive Ones III 해설 및 풀이 (Python)
Dev Chu
Dev Chu
  • Dev Chu
    Log_Double 7
    Dev Chu
  • 전체
    오늘
    어제
    • LOG LIST (201)
      • log Double 7 (2)
        • notice (1)
        • 회고록 (1)
      • Study (112)
        • 과제 (2)
        • 코딩 테스트 (105)
        • 대규모 시스템 설계 기초 (5)
      • CS (10)
        • 자료구조 & 알고리즘 (4)
        • Design Pattern (2)
        • TIL (4)
      • FrontEnd (26)
        • HTML & CSS (16)
        • JavaScript & jQuery (9)
        • React (1)
      • BackEnd (24)
        • Java (4)
        • Python (6)
        • Database (0)
        • Spring (6)
      • Infra & DevOps (3)
        • AWS (3)
        • Git (8)
      • Project (4)
        • repo_bis (2)
        • WhiteMonday (2)
      • ETC (20)
        • TIP (13)
        • Error (5)
        • SQLD (2)
  • 블로그 메뉴

    • 코딩 테스트
  • 링크

    • GitHub
  • 공지사항

    • Log Double 7
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Dev Chu
[LeetCode] 1493. Longest Subarray of 1's After Deleting One Element 해설 및 풀이 (Python)
상단으로

티스토리툴바