Leetcode 1586 Solution

This article provides solution to leetcode question 1586 (longest-subarray-of-1s-after-deleting-one-element)

https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element

Solution

class Solution:
    def getOpt(self, nums):
        opts = []

        for i, num in enumerate(nums):
            if num == 0:
                opt = 0
            else:
                opt = 1 + (opts[i - 1] if i >= 1 else 0)
            opts.append(opt)

        return opts

    def longestSubarray(self, nums: List[int]) -> int:
        if len(nums) == 1:
            return 0

        opt1 = self.getOpt(nums)
        opt2 = list(reversed(self.getOpt(list(reversed(nums)))))

        ans = 0
        for i in range(len(nums)):
            if i == 0:
                ans = max(ans, opt1[1])
            elif i == len(nums) - 1:
                ans = max(ans, opt2[i - 1])
            else:
                ans = max(ans, opt1[i - 1] + opt2[i + 1])
        return ans