leetcode

Max Consecutive Ones - Link

Question Description

Given a binary array nums, return the maximum number of consecutive 1’s in the array.


Constraints


Approach

Use a sliding window approach with two counters:

  1. freq - tracks the current count of consecutive 1’s
  2. count - tracks the maximum count seen so far

For each element in the array:

This approach works because we only need to track the current streak of consecutive 1’s and the maximum streak encountered. When we encounter a 0, the current streak breaks and we start counting from 0 again.


Dry Run

Example Input: nums = [1,1,0,1,1,1]

Step-by-step execution:

Final Answer = 3


Solution

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int count=0;
        int freq=0;
        for(int i=0; i<nums.length; i++){
            if(nums[i]==1) freq++;
            else freq=0;
            count=Math.max(count, freq);
        }   
        return count;     
    }
}

Time and Space Complexity