![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a02ee200efae123e576447e7af0ec407.png)
解法一:暴力遍历
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int res=0,temp=0;
auto it=nums.begin();
while(it!=nums.end()){
if(*(it++)==1) ++temp;
else {
res=max(res,temp);
temp=0;
}
}
res=max(res,temp);
return res;
}
};
解法二:双指针法(滑动窗口)
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int l=0,r=0;
int res=0;
int n=nums.size();
while(r<n){
if(nums[r]==1) r++;
else{
l=++r;
}
res=max(res,r-l);
}
return res;
}
};
解法三:动态规划
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
vector<int> dp(nums.size()+1,0);
if(nums[0]==1) dp[0]=1;
else dp[0]=0;
int res=dp[0];
for(int ii=1;ii<nums.size();ii++){
if(nums[ii]==nums[ii-1]&&nums[ii]==1) dp[ii]=dp[ii-1]+1;
else if(nums[ii]==1) dp[ii]=1;
else if(nums[ii]==0) dp[ii]=0;
if(dp[ii]>res) res=dp[ii];
}
return res;
}
};