[LeetCode] 1004. Max Consecutive Ones III
Given a binary array nums
and an integer k
, return the maximum number of consecutive 1
's in the array if you can flip at most k
0
's.
Example 1:
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Constraints:
1 <= nums.length <= 105
nums[i]
is either0
or1
.0 <= k <= nums.length
最大连续 1 的个数 III。
给定一个二进制数组 nums
和一个整数 k
,如果可以翻转最多 k
个 0
,则返回 数组中连续 1
的最大个数 。
题目问的是如果最多可以翻转其中 k 个数字,能凑成的连续 1 的长度是多少,那么我们可以反过来思考,我们找数组中的 0,找到一个就翻转一个,当翻转的次数等于 k 的时候,我们看看此时 end 和 start 指针的距离是多少,这个距离就是把已经遍历到的 k 个 0 都翻转成 1 之后,能组成的最长的连续 1 的个数。代码还是套用76题的模板即可。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int longestOnes(int[] nums, int k) { 3 int res = 0; 4 int count = 0; 5 int start = 0; 6 int end = 0; 7 while (end < nums.length) { 8 if (nums[end] == 0) { 9 count++; 10 } 11 end++; 12 while (count > k) { 13 if (nums[start] == 0) { 14 count--; 15 } 16 start++; 17 } 18 res = Math.max(res, end - start); 19 } 20 return res; 21 } 22 }
LeetCode中有如下一些题目,求的是连续出现的数字或者字母最长可以组成的子串长度,本质上还是滑动窗口类型的题目。
1004. Max Consecutive Ones III