Max Consecutive Ones

Problem

Find the maximum number of consecutive 1s in a binary array.

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

Python Solution

def max_consecutive_ones(nums):
    best = current = 0
    for num in nums:
        current = current + 1 if num == 1 else 0
        best = max(best, current)
    return best

C++ Solution

int maxConsecutiveOnes(vector<int>& nums) {
    int best = 0, current = 0;
    for (int num : nums) {
        current = (num == 1) ? current + 1 : 0;
        best = max(best, current);
    }
    return best;
}

Java Solution

class Solution {
    public int maxConsecutiveOnes(int[] nums) {
        int best = 0, current = 0;
        for (int num : nums) {
            current = (num == 1) ? current + 1 : 0;
            best = Math.max(best, current);
        }
        return best;
    }
}

Complexity

Time: O(n) — one pass, resetting a counter on every 0. Space: O(1) — two running variables only.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.