题目地址:https://leetcode-cn.com/problems/max-consecutive-ones-ii/

题目描述

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:

  1. The input array will only contain 0 and 1.
  2. 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?

题目大意

最多可以把数组中的一个0翻转成1,求能够成的最长连续1有多少。

解题方法

动态规划

我第一遍做这个题的时候,使用的是从左向右和从右向左两次遍历,找出每个0的左右两部分连续1的个数相加。这样也能过,但是有点麻烦。

比较好的解决方案是动态规划,定义两个变量left, right。

  1. left的含义是:遇到了0,并翻转了该0时,包含该0的位置和其左侧连续的1的的长度。
  2. right的含义是:从上次遇到0之后,累加得到的连续1的个数。

举例说明:

1 0 1 1 0
left start left end right start right end, i

维护两个变量:

  1. 当遇到1时,用right保存已经遇到的连续的1(不含翻转0得到的1)。
  2. 当遇到0时,把这个0翻转,更新left为right + 1(把位置的0翻转为1),更新right为0。

left+right的最大值即为所求。

C++代码如下:

class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
const int N = nums.size();
if (N == 0) return 0;
int left = 0, right = 0;
int res = 0;
for (int i = 0; i < N; ++i) {
if (nums[i] == 1) {
right++;
} else {
left = right + 1;
right = 0;
}
res = max(res, left + right);
}
return res;
}
};

参考资料:https://www.cnblogs.com/grandyang/p/6376115.html

日期

2019 年 9 月 21 日 —— 莫生气,我若气病谁如意

最新文章

  1. sqlserver中的表值函数和标量值函数
  2. 烂泥:centos安装及配置DNS服务器
  3. Yii源码阅读笔记(十七)
  4. 将自定义的 service provider 绑定到 IOC 容器
  5. 多线程(一)NSThread
  6. A Very Easy Triangle Counting Game
  7. [Leetcode]-ReverseLinkedList
  8. js 仿 asp中的 asc 和 chr 函数的代码
  9. 强制性输出private中变量的三种方法
  10. 2016大连网络赛 Weak Pair
  11. Pandas日期数据处理:如何按日期筛选、显示及统计数据
  12. 538. Convert BST to Greater Tree
  13. (1-1)SpringCloud-Eureka:服务的注册与发现
  14. codeforces 286E Ladies&#39; Shop
  15. 浅析vue2.0的diff算法
  16. 利用js给datalist或select动态添加option选项
  17. [C#]中获取当前程序运行路径的方法
  18. 对hadoop namenode -format执行过程的探究
  19. 雷林鹏分享:C# 判断
  20. OpenSSL开发学习总结

热门文章

  1. R 多图间距调整
  2. EXCEl-数据透视表按照自定义序列排序
  3. 32-3Sum
  4. Bebug与Release版本
  5. Excel-计算年龄、工龄 datedif()
  6. LeetCode两数之和
  7. git 的基本流程
  8. Ubantu nodejs卸载与二进制安装
  9. Actuator监控器
  10. 【Linux】【Services】【Project】Cobbler自动化装机