# 0487. Max Consecutive Ones II ###### tags: `Leetcode` `Medium` `Sliding Window` `Dynamic Programming` Link: https://leetcode.com/problems/max-consecutive-ones-ii/ ## 思路 ### Sliding Window 和[1004. Max Consecutive Ones III](https://hackmd.io/LbO10-8UTDWGIJX2A4cEfA)很像 可以用一样的sliding window方法写 要和[1156. Swap For Longest Repeated Character Substring](https://hackmd.io/R4opMwT2Qg-a-PnLmsS59g)区分开,不需要用那么麻烦的方法写 ### Dynamic Programming To do or not to do题型 count1是目前为止不行使flip权利的最长consecutive ones count2是目前为止行使flip权利的最长consecutive ones 如果num=1 显然count1和count2直接加1就可以了 如果num=0 count2=count1+1(行使权利) count1直接清零 在过程中记录最大的count2 ## Code ```java= class Solution { public int findMaxConsecutiveOnes(int[] nums) { int count1=0, count2=0; int ans=0; for(int num:nums){ if(num==1){ count1+=1; count2+=1; } else{ count2=count1+1; count1=0; } ans = Math.max(ans, count2); } return ans; } } ```