Skip to main content

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

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

Python

  1. [0,1,1,1,0,1,1,0,1] => "011101101"
  2. segments ['', '111', '11', '1'] => counts [0, 3, 2, 1]
  3. Copy and offset the counts, then get the max of the sums
      [0, 0, 3, 2, 1]  # [0]+counts
    + [0, 3, 2, 1, 0] # counts+[0]
    = [0, 3, 5, 3, 1] # sums
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
if 0 not in nums:
return len(nums)-1

segments = ''.join(map(str, nums)).split('0')
counts = [len(seg) for seg in segments]

return max([
pair[0]+pair[1]
for pair
in zip([0]+counts, counts+[0])
])