【编程题】找出二进制数组中连续1的最大长度

   |   1 minute read   |   Using 115 words

【编程题】找出二进制数组中连续1的最大长度

Max Consecutive(连续的) Ones

Given a binary array nums,

return the maximum number of consecutive 1’s in the array.

Example 1:

Input: nums = [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.

Example 2:

Input: nums = [1,0,1,1,0,1]
Output: 2

#include <iostream>
#include <vector>

using namespace std;

int findMaxConsecutiveOnes(vector<int>& nums) {
    int count = 0;
    int max_num = 0;

    for(int i = 0; i < nums.size(); i++){
        if(nums[i] == 1){
           count++;
       }else{
           count = 0;
        };
        max_num = max(count,max_num);
    }

    cout <<  max_num << endl;
    return 0 ;
}

int main(){

    vector<int> nums{1,0,0,1,1,0,1,1,1,0,1,1,1,1};

    findMaxConsecutiveOnes(nums);

    return 0;
}

output

4


© 2025 by clayliu. All Rights Reserved.