(leetcode題解)Max Consecutive Ones

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

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:this

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

題意是在一個二進制數組中,找到此數組中連續1的最大數。spa

這個循環一遍記錄最大連續值便可,C++實現以下:code

    int findMaxConsecutiveOnes(vector<int>& nums) {
        int count=0;
        int max=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]==1)
            {
                count++;
            }
            else
            {
                count=0;
            }
            if(count>max)
                    max=count;
        }
        return max;
    }
相關文章
相關標籤/搜索