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& 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;
}

你可能感兴趣的:(485. Max Consecutive Ones)