Problem
Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0.
Example 1:
Input: [1,0,1,1,0]
Output: 4
Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
After flipping, the maximum number of consecutive 1s is 4.
Note:
The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000
Follow up:
What if the input numbers come in one by one as an infinite stream? In other words, you can"t store all numbers coming from the stream as it"s too large to hold in memory. Could you solve it efficiently?
class Solution { public int findMaxConsecutiveOnes(int[] nums) { int max = 0, lastZeroIndex = -1; int l = 0, r = 0; while (r < nums.length) { if (nums[r] == 0) { l = lastZeroIndex+1; lastZeroIndex = r; } max = Math.max(max, r-l+1); r++; } return max; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72691.html
Max Consecutive Ones 题目链接:https://leetcode.com/problems... public class Solution { public int findMaxConsecutiveOnes(int[] nums) { // loop invariant: // global is the max so far, ...
摘要:题目链接题目分析给定一个二进制数组只含有和的数组,返回最长的串。思路逐个遍历,若为则计数。遇到则判断当前计数是否大于之前记录的最大数字,并置零。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D67 485. Max Consecutive Ones 题目链接 485. Max Consecutive Ones 题目分析 给定一个二进制数组(只含有0和1的数组),返回最长的1串。 思...
摘要:示例输入输出解释开头的两位和最后的三位都是连续,所以最大连续的个数是注意输入的数组只包含和。输入数组的长度是正整数,且不超过。 公众号:爱写bug 给定一个二进制数组, 计算其中最大连续1的个数。 Given a binary array, find the maximum number of consecutive 1s in this array. 示例 1: 输入: [1,1,0...
摘要:示例输入输出解释开头的两位和最后的三位都是连续,所以最大连续的个数是注意输入的数组只包含和。输入数组的长度是正整数,且不超过。 公众号:爱写bug 给定一个二进制数组, 计算其中最大连续1的个数。 Given a binary array, find the maximum number of consecutive 1s in this array. 示例 1: 输入: [1,1,0...
摘要:示例输入输出解释开头的两位和最后的三位都是连续,所以最大连续的个数是注意输入的数组只包含和。输入数组的长度是正整数,且不超过。 公众号:爱写bug 给定一个二进制数组, 计算其中最大连续1的个数。 Given a binary array, find the maximum number of consecutive 1s in this array. 示例 1: 输入: [1,1,0...
阅读 1448·2021-11-17 09:33
阅读 1246·2021-10-11 10:59
阅读 2875·2021-09-30 09:48
阅读 1887·2021-09-30 09:47
阅读 3003·2019-08-30 15:55
阅读 2306·2019-08-30 15:54
阅读 1473·2019-08-29 15:25
阅读 1629·2019-08-29 10:57