一次遍历法
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int consecutive_ones = nums[0] == 1? 1:0;
int max = consecutive_ones;
for(int i = 1;i<nums.length; i++){
if( nums[i] ==1){
consecutive_ones += 1;
}
else{
consecutive_ones =0;
}
max = Math.max(max,consecutive_ones);
}
return max;
}
}
动态规划法
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
nums[0] = nums[0]== 1?1:0;
int consecutive_one = nums[0];
for(int i=1;i<nums.length;i++){
if(nums[i]==1){
nums[i]=nums[i-1]+1;
}
else{
nums[i]=0;
}
consecutive_one =Math.max(consecutive_one,nums[i]);
}
return consecutive_one;
}
}