Question
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
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
int findMaxConsecutiveOnes(int* nums, int numsSize) {
int i, sum = 0,index=0;
int numsSum[numsSize];
for (i = 0; i < numsSize; i++)
numsSum[i]=0;
for (i = 0; i < numsSize; i++) {
if (nums[i]) {
++sum;
} else {
numsSum[index++] = sum;
sum=0;
}
}
numsSum[numsSize-1] = sum;
sum = 0;
for (i = 0; i < numsSize; i++)
sum=numsSum[i]>sum?numsSum[i]:sum;
return sum;
}
Solution best of others
简洁明了
int findMaxConsecutiveOnes(int* nums, int numsSize) {
int curMax = 0;
int max;
for(int i = 0; i < numsSize; i++) {
curMax = curMax * nums[i] + nums[i];
if(curMax > max) {
max = curMax;
}
}
return max;
}