LeetCode 题解工作台
删掉一个元素以后全为 1 的最长子数组
给你一个二进制数组 nums ,你需要从中删掉一个元素。 请你在删掉元素的结果数组中,返回最长的且只包含 1 的非空子数组的长度。 如果不存在这样的子数组,请返回 0 。 提示 1: 输入: nums = [1,1,0,1] 输出: 3 解释: 删掉位置 2 的数后,[1,1,1] 包含 3 个 1…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们可以枚举每个删除的位置 ,然后计算左侧和右侧的连续 1 的个数,最后取最大值。 具体地,我们使用两个长度为 的数组 和 ,其中 表示以 结尾的连续 的个数,而 表示以 开头的连续 的个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个二进制数组 nums ,你需要从中删掉一个元素。
请你在删掉元素的结果数组中,返回最长的且只包含 1 的非空子数组的长度。
如果不存在这样的子数组,请返回 0 。
提示 1:
输入:nums = [1,1,0,1] 输出:3 解释:删掉位置 2 的数后,[1,1,1] 包含 3 个 1 。
示例 2:
输入:nums = [0,1,1,1,0,1,1,0,1] 输出:5 解释:删掉位置 4 的数字后,[0,1,1,1,1,1,0,1] 的最长全 1 子数组为 [1,1,1,1,1] 。
示例 3:
输入:nums = [1,1,1] 输出:2 解释:你必须要删除一个元素。
提示:
1 <= nums.length <= 105nums[i]要么是0要么是1。
解题思路
方法一:枚举
我们可以枚举每个删除的位置 ,然后计算左侧和右侧的连续 1 的个数,最后取最大值。
具体地,我们使用两个长度为 的数组 和 ,其中 表示以 结尾的连续 的个数,而 表示以 开头的连续 的个数。
最终答案即为 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
left = [0] * (n + 1)
right = [0] * (n + 1)
for i, x in enumerate(nums, 1):
if x:
left[i] = left[i - 1] + 1
for i in range(n - 1, -1, -1):
if nums[i]:
right[i] = right[i + 1] + 1
return max(left[i] + right[i + 1] for i in range(n))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
They mention keeping a window with at most one zero, which points directly to the one-deletion sliding window.
- question_mark
They ask what happens on an all-ones array, testing whether you remember the deletion is mandatory.
- question_mark
They ask for an O(N) solution without extra arrays, which favors constant-space state transitions.
常见陷阱
外企场景- error
Returning the longest run of 1s without subtracting one when the current window contains no zero.
- error
Treating the task as optional deletion and incorrectly answering 3 for nums = [1,1,1].
- error
Resetting too aggressively on zeros and missing that one deleted zero can merge the left and right 1-runs.
进阶变体
外企场景- arrow_right_alt
Allow deleting up to k elements, which generalizes the window from at most one zero to at most k zeros.
- arrow_right_alt
Return the actual subarray boundaries after deletion instead of only the maximum length.
- arrow_right_alt
Solve the streaming version where bits arrive one by one and you maintain the current best under one deletion.