LeetCode 1004. Max Consecutive Ones III
2024-10-21 04:08:57
原题链接在这里: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 <= A.length <= 20000
0 <= K <= A.length
A[i]
is0
or1
题解:
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;
}
}
最新文章
- nginx转发会 默认忽略 headers 中name带&rdquo;_&rdquo;的
- POJ 2421(prim)
- [CareerCup] 18.11 Maximum Subsquare 最大子方形
- 批量删除wordpress垃圾评论留言
- html 绘制图像
- java 字符串 转码
- 无需操作系统和虚拟机,直接运行Python代码
- Fix Windows 7 Msvcp71.dll And Msvcr71.dll Missing Error
- oracle数据库连接串格式
- 关于db2处理特殊字段出现异常java.io.charConversionException
- python之生成器和列表推导式
- dom操作节点之常用方法
- 线程的条件Condiition
- js检测字符串的字节数
- PHP中VC6、VC9、TS、NTS版本区别与用法
- 22.python中的面向对象和类的基本语法
- PHP接收跨域请求header 头设置
- 关于LNMP常见问题和性能方面的个人理解
- javascript工厂模式、单例模式
- 使用ASM获得JAVA类方法参数名