Coding Exercise – Find Max Consecutive Ones


learn-to-code Coding Exercise - Find Max Consecutive Ones c / c++ coding exercise learn to code python

learn-to-code

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

We count of the current consecutive 1s and the maximum count when iterating the numbers from left to right. If current element is 1, we increment the counter and compare to the maximum. Otherwise, we reset the current counter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        auto r = 0, m1 = 0;
        for (auto n: nums) {
            if (n == 1) {
                r ++;
                m1 = max(m1, r);
            } else {
                r = 0;
            }
        }
        return m1;
    }
};
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        auto r = 0, m1 = 0;
        for (auto n: nums) {
            if (n == 1) {
                r ++;
                m1 = max(m1, r);
            } else {
                r = 0;
            }
        }
        return m1;
    }
};

Using Python, this can be solved in a slightly different way – join the array as a string, split by delimiter ‘0’ and get the maximum length of the 1s.

1
return max([len(i) for i in "".join(map(str, nums)).split('0')])
return max([len(i) for i in "".join(map(str, nums)).split('0')])

You may also like: C++ 编程练习题 – 最多连续的 1

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
285 words
Last Post: C++ Coding Exercise - Sum of Left Leaves (BFS + DFS + Recursion)
Next Post: C++ Coding Exercise - Find Third Maximum in O(n)

The Permanent URL is: Coding Exercise – Find Max Consecutive Ones

Leave a Reply