刷题-力扣-485

485. 最大连续1的个数

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-consecutive-ones/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

给定一个二进制数组, 计算其中最大连续1的个数。

示例 1:

输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.

注意:

输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,00

题目分析

  1. 根据题目描述求最长连续的1
  2. now记录局部连续的1的长度,max记录最长的连续1的长度
  3. 遍历nums,即可求出最长连续的1

代码

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int max = 0;
        int now = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == 1) now++;
            else {
                max = max > now ? max : now;
                now = 0;
            }
        }
        return max > now ? max : now;
    }
};
posted @ 2021-02-15 20:07  韩亚光  阅读(37)  评论(0编辑  收藏  举报