Description

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

Example 1:

1Input: nums = [1,1,0,1,1,1]
2Output: 3
3Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.

Example 2:

1Input: nums = [1,0,1,1,0,1]
2Output: 2

Constraints:

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1.

Solution

This is relatively simple case where if the number is 1, we have to increase currentLength. If we have found 1s, then we increment currentLength and replace maxLength with currentLength if it’s longer.

 1class Solution {
 2    public int findMaxConsecutiveOnes(int[] nums) {
 3        int currentLength = 0;
 4        int maxLength = 0;
 5        for (int i = 0; i < nums.length; i++) {
 6            if (nums[i] == 0) {
 7                currentLength = 0;
 8            } else {
 9                currentLength++;
10                maxLength = Math.max(maxLength, currentLength);
11            }
12        }
13        return maxLength;
14    }
15}