Longest Subarray of 1s After Deleting One Element

Medium · Sliding Window · Array · Dynamic Programming · Sliding Window

Problem

Given a binary array nums, you must delete exactly one element from it.

Return the length of the longest run of consecutive 1s in what remains, or 0 if no 1 remains.

Examples

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

Deleting the 0 at index 1 joins the 1 before it with the two 1s after it.

Input: nums = [1,1,1]
Output: 2

One element must be deleted even though every element is a 1.

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

There are no 1s at all.

Constraints

Approaches

Follow-up

What if you may delete up to k elements, all of them zeros? The same window allows k zeros, and the answer becomes the window length minus the zeros it holds. If instead you flip a zero into a 1, nothing is removed and the full window length counts; see the use case "Longest run of 1s after turning one 0 into a 1".

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…