All problems

Longest Subarray of 1's After Deleting One Element

Medium · sliding window

A list nums holds only the numbers 0 and 1.

You must remove exactly one element from it, and you choose which one. The elements on either side of the gap then close up and become neighbours. After that, look at the longest stretch of neighbouring ones in the list that is left.

Return the greatest length that stretch can have, over every element you could have removed. If no ones are left, return 0.

Examples

Example 1

Input: nums = [1, 1, 0, 1, 1, 1]

Output: 5

Remove the zero. The two stretches of ones join into five in a row.

Example 2

Input: nums = [1, 0, 0, 1, 1]

Output: 2

There are two zeros in a row, so removing one of them joins nothing. The best you can do is keep the two ones at the end.

Example 3

Input: nums = [1, 1, 1]

Output: 2

You still have to remove one element, so a list of three ones leaves two.

Constraints