[Leetcode]1493. Longest Subarray of 1's After Deleting One Element

2024. 8. 3. 10:53Algorithm

1. problem :

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

 

2. solution 1 :

from typing import List

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        left = 0
        zero_count = 0
        max_length = 0
        
        for right in range(len(nums)):
            if nums[right] == 0:
                zero_count += 1
                
            while zero_count > 1:
                if nums[left] == 0:
                    zero_count -= 1
                left += 1
            
            # 현재 윈도우에서 삭제한 0을 하나 포함한 상태의 1의 최대 길이 업데이트
            max_length = max(max_length, right - left)
        
        return max_length

# 예제 테스트
print(Solution().longestSubarray([1,1,0,1]))  # 출력: 3
print(Solution().longestSubarray([0,1,1,1,0,1,1,0,1]))  # 출력: 5
print(Solution().longestSubarray([1,1,1]))  # 출력: 2

 

2. solution 2 :

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        if len(nums) == nums.count(1):
            return len(nums) - 1
        last_zero_prev = 0 
        count = 0 
        result = []
        for i in range(len(nums)):
            if nums[i] == 0:
                result.append(count)
                count -= last_zero_prev 
                last_zero_prev = count 
            else:
                count += 1 
        result.append(count)
        return max(result)

'Algorithm' 카테고리의 다른 글

[Boj]1475 :방 번호  (0) 2024.08.04
[Leetcode]981. Time Based Key-Value Store  (0) 2024.08.03
[Leetcode] 875. Koko Eating Bananas(x)  (0) 2024.08.03
[Leetcode]704. Binary Search  (0) 2024.08.02
[Leetcode]84. Largest Rectangle in Histogram(x)  (0) 2024.08.02