485. Max Consecutive Ones
题目概述
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
nput: [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 and 1.
The length of input array is a positive integer and will not exceed 10,000
Subscribe to see which companies asked this question.
算法思想
- 记录数组中连续1的值
- 记录数组中最大的连续1的值
- 遍历数组,遇1则加,遇0则置为0
- 返回最大连续1的值
代码实现
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int sum=0;//记录连续的1值
int maxsum=0;//记录最大的连续1值
for(int i=0; i<nums.size(); i++){
if(nums[i]==1) sum+=1;//遇1则加
if(sum>maxsum) maxsum=sum;//判断是否大于当前最大连续值
if(nums[i]==0) sum=0;//遇0则置为0
}
return maxsum;
}
};