O(N) time & O(1) space My solution should be able to work for follow up


  • 0
    C

    Using left and right to keep storing number of 1s on the left of 0 and right of 0.

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int left = 0;
            int right = 0;
            int res = 0;
            while (left < nums.length) {
                if (nums[left] == 1)
                    left++;
                else
                    break;
            }
            res = left;
            for (int i = left; i < nums.length - (res - left);) {
                int j = i + 1;
                while (j < nums.length && nums[j] == 1) {
                    j++;
                }
                right = j - i - 1;
                res = Math.max(res, left + right + 1);
                i = j;
                left = right;
                right = 0;
            }
            return res;
        }
    }
    

Log in to reply
 

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