LeetCode 题解工作台

最大连续1的个数 III

给定一个二进制数组 nums 和一个整数 k ,假设最多可以翻转 k 个 0 ,则返回执行操作后 数组中连续 1 的最大个数 。 示例 1: 输入: nums = [1,1,1,0,0,0,1,1,1,1,0], K = 2 输出: 6 解释: [1,1,1,0,0, 1 ,1,1,1,1, 1 ]…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·搜索·答案·空间

bolt

答案摘要

我们可以遍历数组,用一个变量 记录当前窗口中 0 的个数,当 $\textit{cnt} > k$ 时,我们将窗口的左边界右移一位。 遍历结束后,窗口的长度即为最大连续 1 的个数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个二进制数组 nums 和一个整数 k,假设最多可以翻转 k0 ,则返回执行操作后 数组中连续 1 的最大个数

 

示例 1:

输入:nums = [1,1,1,0,0,0,1,1,1,1,0], K = 2
输出:6
解释:[1,1,1,0,0,1,1,1,1,1,1]
粗体数字从 0 翻转到 1,最长的子数组长度为 6。

示例 2:

输入:nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
输出:10
解释:[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
粗体数字从 0 翻转到 1,最长的子数组长度为 10。

 

提示:

  • 1 <= nums.length <= 105
  • nums[i] 不是 0 就是 1
  • 0 <= k <= nums.length
lightbulb

解题思路

方法一:滑动窗口

我们可以遍历数组,用一个变量 cnt\textit{cnt} 记录当前窗口中 0 的个数,当 cnt>k\textit{cnt} > k 时,我们将窗口的左边界右移一位。

遍历结束后,窗口的长度即为最大连续 1 的个数。

注意,在上述过程中,我们不需要循环将窗口的左边界右移,而是直接将左边界右移一位,这是因为,题目求的是最大连续 1 的个数,因此,窗口的长度只会增加,不会减少,所以我们不需要循环右移左边界。

时间复杂度 O(n)O(n),其中 nn 为数组的长度。空间复杂度 O(1)O(1)

相似题目:

1
2
3
4
5
6
7
8
9
10
class Solution:
    def longestOnes(self, nums: List[int], k: int) -> int:
        l = cnt = 0
        for x in nums:
            cnt += x ^ 1
            if cnt > k:
                cnt -= nums[l] ^ 1
                l += 1
        return len(nums) - l
speed

复杂度分析

指标
时间complexity is O(n) for sliding window, O(n log n) if using binary search over window size, and space complexity is O(1) for sliding window or O(n) for prefix sum. Each method aligns with the maximum-consecutive-ones pattern and handles large input efficiently.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Focus on maximizing 1s using minimal zero flips.

  • question_mark

    Consider the sliding window as the main pattern for handling consecutive sequences.

  • question_mark

    Be aware of off-by-one errors when adjusting the window boundaries.

warning

常见陷阱

外企场景
  • error

    Flipping zeros that do not extend a 1s sequence, wasting k flips.

  • error

    Failing to shrink the window correctly when zero count exceeds k.

  • error

    Incorrectly updating maximum length after window adjustment.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the subarray itself instead of its length.

  • arrow_right_alt

    Allow flipping zeros with different weights or costs.

  • arrow_right_alt

    Find maximum consecutive ones for multiple queries of k in the same array.

help

常见问题

外企场景

最大连续1的个数 III题解:二分·搜索·答案·空间 | LeetCode #1004 中等