Max Consecutive Ones | Array Problem | LeetCode 485

4 years ago Lalit Bhagtani 0

Problem Statement

You have given an integer array comprising of 1 and 0 integers only, write a program to find out the maximum number of consecutive 1’s in the given array.

Example 

Max Consecutive Ones

Input :- [1, 1, 0, 1, 1, 1]
Output :- 3
Input :- [0, 1, 1, 0, 1, 0, 1, 1]
Output :- 2

Solution

The Max Consecutive Ones can be solved using sliding window technique, steps to solve this problem are as follows :-

  1. Traverse the input array from start to end, at each iteration check if the current element is 1 or 0.
  2. If the current element is 1, then increase the size of the sliding window by 1 (increase the count variable by 1).
  3. If the current element is 0, then check if the size of the sliding window (value of count variable) is greater than the current maximum or not, if yes then update the maximum and make the size of the sliding window as zero (assign 0 to count variable).
  4. After the end of the input array traversal, repeat the condition of step 3 and return the current maximum as a result.

Program

public class Main {

	public static void main(String[] args) {
		Main main = new Main();
		int result = main.findMaxConsecutiveOnes(new int[] {0, 1, 1, 0, 1, 0, 1, 1});
		System.out.println(result);
	}

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

Result

2

That’s all for Max Consecutive Ones in Java, If you liked it, please share your thoughts in a comments section and share it with others too.