PU Max Consecutive Ones

Jan 01, 1970

Given a binary array, find the maximum number of consecutive 1s in this array.

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

Example:

  • 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.

C Solution 1:

int findMaxConsecutiveOnes(int* nums, int numsSize) {
    int max = 0;
    int i = nums[0] ? -1 : 0;
    int j;
    for (j = 1; j < numsSize; j++) {
        if (nums[j]) continue;
        max = max > j - i - 1 ? max : j - i - 1;
        i = j;
    }
    max = max > j - i - 1 ? max : j - i - 1;
    return max;
}

C Solution 2:

int findMaxConsecutiveOnes(int* nums, int numsSize) {
    int max = 0, _max = 0;
    int i;
    for (i = 0; i < numsSize; i++) {
        if (nums[i]) _max++;
        else {
            max = max > _max ? max : _max;
            _max = 0;
        }
    }
    max = max > _max ? max : _max;
    return max;
}

Summary:

  • Check consecutive ones or check two neighboring zeros.

LeetCode: 485. Max Consecutive Ones