less than 1 minute read

1493. Longest Subarray of 1’s After Deleting One Element (medium)

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        temp = []
        n = len(nums)

        if len(set(nums)) == 1 and nums[0] == 1:
            return n - 1

        i = 0 
        while i < n:
            cur = nums[i]
            j = i
            while j < n and nums[j] == cur:
                j += 1
            temp.append((cur, j - i))
            i = j
        
        # print(temp)
        res = 0
        m = len(temp)
        for index, value in enumerate(temp):
            if value[0] == 0:
                a = temp[index - 1][1] if index - 1 >= 0 else 0
                b = temp[index + 1][1] if index + 1 < m else 0
                if value[1] == 1:
                    res = max(res, a + b)
            if value[0] == 1:
                res = max(res, value[1])

        return res