Max Consecutive Ones – Leetcode #485

Problem Statement

This problem is from Leetcode – Max Consecutive Ones. The problem statement is as below:

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

Solution

Initialize variables

  1. max – It keeps track of maximum number of consecutive 1’s in the array. This is our answer.
  2. count – It keep track of number of consecutive 1s until a 0 is encountered.

Iterate Though the Array

  1. If 1 is encountered, increment count.
  2. If 0 is encountered, reset count.
  3. If max is less than count, then update max.
public int findMaxConsecutiveOnes(int[] nums) {
        
		int max = 0;
		
		int count = 0;
		for(int i=0; i<nums.length; i++) {
			
			// keep count of consecutive 1s
			if(nums[i] == 1) {
				
				count = count+1;
			}
			
			// reset count if 0 is encountered
			if(nums[i] == 0) {
				
				count = 0;
							
			}
			
			// update max
			max = Math.max(max, count);
		}
		
		return max;
    }

You can checkout the code from Github here: Max Consecutive Ones. See the performance of this approach below:

Max Consecutive Ones  -  Leetcode #485

See the complexity of this approach below:

Max Consecutive Ones  -  Leetcode #485

Leave a Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top