1004:最大连续1的个数 III

This commit is contained in:
huangge1199 2021-09-01 16:58:54 +08:00
parent 047cd5b172
commit 145a8f35e6
2 changed files with 95 additions and 0 deletions

View File

@ -0,0 +1,63 @@
//给定一个由若干 0 1 组成的数组 A我们最多可以将 K 个值从 0 变成 1
//
// 返回仅包含 1 的最长连续子数组的长度
//
//
//
// 示例 1
//
// 输入A = [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
//
// 输入A = [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 <= A.length <= 20000
// 0 <= K <= A.length
// A[i] 0 1
//
// Related Topics 数组 二分查找 前缀和 滑动窗口 👍 316 👎 0
package leetcode.editor.cn;
//1004:最大连续1的个数 III
class MaxConsecutiveOnesIii {
public static void main(String[] args) {
//测试代码
Solution solution = new MaxConsecutiveOnesIii().new Solution();
solution.longestOnes(new int[]{0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1}, 3);
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int longestOnes(int[] nums, int k) {
int index = 0, lsum = 0, rsum = 0;
int count = 0;
for (int i = 0; i < nums.length; ++i) {
rsum += 1 - nums[i];
while (lsum < rsum - k) {
lsum += 1 - nums[index];
index++;
}
count = Math.max(count, i - index + 1);
}
return count;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,32 @@
<p>给定一个由若干 <code>0</code><code>1</code> 组成的数组&nbsp;<code>A</code>,我们最多可以将&nbsp;<code>K</code>&nbsp;个值从 0 变成 1 。</p>
<p>返回仅包含 1 的最长(连续)子数组的长度。</p>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<pre><strong>输入:</strong>A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
<strong>输出:</strong>6
<strong>解释: </strong>
[1,1,1,0,0,<strong>1</strong>,1,1,1,1,<strong>1</strong>]
粗体数字从 0 翻转到 1最长的子数组长度为 6。</pre>
<p><strong>示例 2</strong></p>
<pre><strong>输入:</strong>A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
<strong>输出:</strong>10
<strong>解释:</strong>
[0,0,1,1,<strong>1</strong>,<strong>1</strong>,1,1,1,<strong>1</strong>,1,1,0,0,0,1,1,1,1]
粗体数字从 0 翻转到 1最长的子数组长度为 10。</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ol>
<li><code>1 &lt;= A.length &lt;= 20000</code></li>
<li><code>0 &lt;= K &lt;= A.length</code></li>
<li><code>A[i]</code>&nbsp;<code>0</code>&nbsp;&nbsp;<code>1</code>&nbsp;</li>
</ol>
<div><div>Related Topics</div><div><li>数组</li><li>二分查找</li><li>前缀和</li><li>滑动窗口</li></div></div><br><div><li>👍 316</li><li>👎 0</li></div>