485 Max Consecutive Ones Maximum number of consecutive 1s

Given a binary array, calculate the maximum number of consecutive 1s in it.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits and the last three digits are consecutive 1s, so the maximum number of consecutive 1s is 3.
Note:
    Input The array contains only 0s and 1s.
    The length of the input array is a positive integer and cannot exceed 10,000.
See: https://leetcode.com/problems/max-consecutive-ones/description/

C++:

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int cnt=0,res=0;
        for(int num:nums)
        {
            cnt=num==0?0:cnt+1;
            res=max(res,cnt);
        }
        return res;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324613978&siteId=291194637