java solution for follow up, O(n)


  • 0

    we have only one chance to do flip so when we meet a "zero", we have two choice:
    choice one: flip it;
    choice two: don't flip it;
    I use a variable "pre" to record the number of choice one and "cur" to record choice two.
    what we should do is compare "pre" of this position numbed zero and the "pre" of next position numbed zero.

    hope it helps~

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            if(nums == null || nums.length == 0) return 0;
            int max = 0;
            int pre = 0;
            int cur = 0;
            int countzero = 0;
            for(int i = 0 ; i < nums.length ; i++) {
                if(nums[i] == 1) {
                    pre++;
                    cur++;
                }else {
                    countzero++;
                    if(countzero == 1) {
                        pre++;
                        cur = 0;
                    }else if(countzero == 2) {
                        max = Math.max(max , pre);
                        pre = cur+1;
                        cur = 0;
                        countzero = 1;
                    }
                }
            }
            return Math.max(max , Math.max(pre , cur));
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.