[Algo] 625. Longest subarray contains only 1s
2024-09-25 22:12:16
Given an array of integers that contains only 0s and 1s and a positive integer k, you can flip at most k 0s to 1s, return the longest subarray that contains only integer 1 after flipping.
Assumptions:
1. Length of given array is between [1, 20000].
2. The given array only contains 1s and 0s.
3. 0 <= k <= length of given array.
Example 1:
Input: array = [1,1,0,0,1,1,1,0,0,0], k = 2
Output: 7
Explanation: flip 0s at index 2 and 3, then the array becomes [1,1,1,1,1,1,1,0,0,0], so that the length of longest subarray that contains only integer 1 is 7.
Example 2:
Input: array = [1,1,0,0,1,1,1,0,0,0], k = 0
Output: 3
Explanation: k is 0 so you can not flip any 0 to 1, then the length of longest subarray that contains only integer 1 is 3.
public class Solution {
public int longestConsecutiveOnes(int[] nums, int k) {
// Write your solution here
int i = 0;
int start = 0;
int count = 0;
int result = 0;
while (i < nums.length) {
if (nums[i] == 0) {
count += 1;
}
while (count > k) {
if (nums[start] == 0) {
count -= 1;
}
start += 1;
}
i += 1;
result = Math.max(result, i - start);
}
return result;
}
}
最新文章
- Rafy 框架-发布网页版用户手册
- asp.net 自定义控件 嵌入资源文件 备忘
- android wifi SWOL低功耗模式
- Effective java 第2版 - 笔记(01) 单例(Singleton)的枚举(enum)实现
- 【原】训练自己haar-like特征分类器并识别物体(1)
- Train Problem I (HDU 100题纪念)
- javascript学习(一) 异常处理与简单的事件
- ZOJ 1042 W’s Cipher
- Paxos算法
- 详谈easyui datagrid增删改查操作
- JS 操作 HTML 自定义属性
- [POJ 3735] Training little cats (结构矩阵、矩阵高速功率)
- kafka生产实践
- css实现文本块在容器中垂直居中
- 移动端热更新方案(iOS+Android)
- PairWork-电梯调度程序结对编程【附加题】
- js 时间戳转特定格式的日期
- Liunx 重定向,管道符(转)
- poj1741(点分模板)
- c#依参数自动生成控件
热门文章
- BlackArch Linux 2019.06.01 宣布发布
- POJ 2593&;&;2479:Max Sequence
- 关于SI4432数据手册的简单讲解
- 一条命令解决:No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
- 二十四、CI框架之URL辅助函数
- hibernate 插入date值到postgresql,丢失时分秒
- HttpClient系列~StringContent与FormUrlEncodedContent
- JavaScript 之 数据在内存中的存储和引用
- POJ 2828 线段树活用
- CSS3 box-shadow 效果大全(内阴影,外阴影,三边阴影,双边阴影,单边阴影,细线描边…)