原题链接在这里:https://leetcode.com/problems/max-consecutive-ones-iii/

题目:

Given an array A of 0s and 1s, we may change up to K values from 0 to 1.

Return the length of the longest (contiguous) subarray that contains only 1s.

Example 1:

Input: A = [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: A = [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.

Note:

  1. 1 <= A.length <= 20000
  2. 0 <= K <= A.length
  3. A[i] is 0 or 1

题解:

Same idea as Max Consecutive Ones II.

Solution is easy to extend from 1 to K.

Time Complexity: O(n). n = A.length.

Space: O(1).

AC Java:

 class Solution {
public int longestOnes(int[] A, int K) {
if(A == null || A.length == 0){
return 0;
} int count = 0;
int walker = 0;
int runner = 0;
int res = 0;
while(runner < A.length){
if(A[runner++] != 1){
count++;
} while(count > K){
if(A[walker++] != 1){
count--;
}
} res = Math.max(res, runner-walker);
} return res;
}
}

最新文章

  1. nginx转发会 默认忽略 headers 中name带&rdquo;_&rdquo;的
  2. POJ 2421(prim)
  3. [CareerCup] 18.11 Maximum Subsquare 最大子方形
  4. 批量删除wordpress垃圾评论留言
  5. html 绘制图像
  6. java 字符串 转码
  7. 无需操作系统和虚拟机,直接运行Python代码
  8. Fix Windows 7 Msvcp71.dll And Msvcr71.dll Missing Error
  9. oracle数据库连接串格式
  10. 关于db2处理特殊字段出现异常java.io.charConversionException
  11. python之生成器和列表推导式
  12. dom操作节点之常用方法
  13. 线程的条件Condiition
  14. js检测字符串的字节数
  15. PHP中VC6、VC9、TS、NTS版本区别与用法
  16. 22.python中的面向对象和类的基本语法
  17. PHP接收跨域请求header 头设置
  18. 关于LNMP常见问题和性能方面的个人理解
  19. javascript工厂模式、单例模式
  20. 使用ASM获得JAVA类方法参数名

热门文章

  1. Qt中 布局管理器失效问题
  2. Java线程本地存储ThreadLocal
  3. Java中new和Class.forName的区别
  4. mvc和mvvm模式
  5. JavaScript之鼠标事件
  6. Java 之 Response 文件下载案例
  7. testNG helloWorld
  8. OpenGL ES教程系列(经典合集)
  9. 【AIX】3004-314 Password was recently used and is not valid for reuse
  10. JS 对象 数组求并集,交集和差集