Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
1 2 3 4 |
Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. |
Note:
- The input array will only contain
0
and1
. - The length of input array is a positive integer and will not exceed 10,000
Solution
This is an easy to solve problem. We keep on counting the ones till a 0 is encountered. And compare the current count of consecutive ones with the previous maximum. Here is the java solution which can be made more concise but for the sake of understanding it is more elaborated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.javagists.learn.interview.questions; public class MaxOnesSolution { public int findMaxConsecutiveOnes(int[] input) { int currentCount = 0; int max = 0; for (int n : input) { currentCount = n == 0 ? 0 : currentCount + 1; max = Math.max(max, currentCount); } return max; } public static void main(String[] args) { int[] input = { 1, 1, 1, 1, 0, 1, 1, 1 }; System.out.println(new MaxOnesSolution().findMaxConsecutiveOnes(input)); } } |
You may also like Java interview questions
References
https://leetcode.com/problems/max-consecutive-ones/