485. Max Consecutive Ones

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.

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

思路:用一个累加器count对所有元素求和,一旦遇到0就清零.用res记录下count的最大值,即可知道序列中最长的连续1有多少.

int findMaxConsecutiveOnes(vector<int>& nums) {
    int count = 0;
    int res = 0;
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] == 0) count = 0;
        count += nums[i];
        if (count > res) res = count;
    }
    return res;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,792评论 0 33
  • 【日更074】开始使用“简书”不久,我就给自己制定了一个“日更计划”,一是想培养一个长期坚持的习惯,二是刻意锻炼“...
    唐斩2086阅读 712评论 0 2
  • 今天,我们开始军训的第四天,在正步踢腿训练,我累得哭了,但很值得!
    我的未来不迷茫阅读 138评论 0 0
  • “白龙弟子…” 牧尘望着那第三道石柱之上缓缓苏醒的石影,眼神渐渐的凝重,身体也是紧绷了起来,强横的灵力荡漾在其周身...
    混沌天书阅读 510评论 0 1
  • 跨了大半个地球的年 在世界的尽头上做着乏力的梦 天黑月明星稀的夜晚,也有微风相伴 红日鸡鸣是幅挂在梦乡的老画 细雨...
    索索闲语阅读 235评论 0 2