Max Consecutive Ones

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


Example 1:

Input: nums = [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.

Example 2:

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


Constraints:

  • 1 <= nums.length <= 105

  • nums[i] is either 0 or 1.

My Solution

We can solve this problem with the sliding window technique. We have two pointers i and j that start at index 0. If we encounter a 1, we increment j. Otherwise, we update our max count with j-i if larger than max and move both i and j to point at the next character. Finally after we are done iterating though the array, we update max again for the last string of 1’s and return our max.

Time complexity is O(n) since we iterate once through the array. Space complexity is O(1) since we only require constant extra space.

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int i = 0;
        int j = 0;
        int n = nums.length;
        int max = 0;

        while (j < n) {
            if (nums[j] != 1) {
                max = Math.max(max, j-i);
                j++;
                i = j;
            }
            else {
                j++;
            }
        }

        max = Math.max(max, j-i);

        return max;
    }
}
Previous
Previous

Smallest Divisible Digit Product

Next
Next

License Key Formatting