Max Consecutive Ones
题目链接:
public class Solution { public int findMaxConsecutiveOnes(int[] nums) { // loop invariant: // global is the max so far, local is the max including current nums[i] int global = 0; int local = 0; for(int i = 0; i < nums.length; i++) { local = (nums[i] == 1 ? local + 1 : 0); global = Math.max(global, local); } return global; }}
Max Consecutive Ones II
题目链接:
public class Solution { public int findMaxConsecutiveOnes(int[] nums) { // 2 points, slide window int i = 0, j = 0; int global = 0; // count the number of flip int count = 0; while(j < nums.length) { if(nums[j++] == 0) count++; while(count > 1) if(nums[i++] == 0) count--; global = Math.max(global, j - i); } return global; }}