Two Pointers: Given a binary array, return maximum consecutive ones

Problem Statement:

You are given a binary array, you need to return the maximum number of consecutive 1s in the array

Example:

Input: arr = [1, 1, 0, 1, 1, 1]

Output: 3

Explanation:

There are 3 consecutive 1s

Solution Explanation:

Solution is very simple.

We will use sliding window with two pointer technique to solve the problem.

Take two pointers and start from position 0, move the right pointer. When nums[right] = 0, then calculate the length by right – left.

Move the right pointer past 0.

Then set left = right, and repeat the step and calculate the maximum consecutive length and return the result.

Time Complexity: O(n)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <string>
#include <climits>

using namespace std;


int solution(vector<int>& nums) 
{
    int left = 0, right = 0, ans = 0;

    int n = nums.size();
    
    while (right < n) 
    {
        if (nums[right] == 0)
        {
            ans = max(ans, right - left);

            while (right < n && nums[right] == 0) 
            	right++;

            left = right;
        } 
        else 
        {
            right++;
        }
    }
    return max(ans, right - left);
}

int main()
{
    vector<int> arr = {1, 1, 0, 1, 1, 1};

    cout << solution(arr);

    return 0;
}

Output

3
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *