leetcode 485.最大连续1的个数

leetcode 485.最大连续1的个数

题干

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

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

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

题解

遍历一遍数组,统计即可

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int n = nums.size();
        int currentLength = 0;
        int ans = 0;
        for(int i = 0 ; i < n ; ++i){
            if(nums[i] == 1){
                currentLength = (currentLength == 0) ? 1 : (currentLength + 1);
                ans = max(ans,currentLength);
            }else{
                currentLength = 0;
            }
        }
        return ans;
    }
};
上一篇:RS-485详解(一)


下一篇:力扣485. 最大连续1的个数-C语言实现-简单题