Java Concise O(n) solution (which can handle input with infinite count)

  • 1

    To handle infinite input, we should not access index of the array.

    I used enhanced for loop, so didn't access index of the array at all.

    The idea is maintaining two buffer. (frontSum and backSum)

    frontSum contains consecutive (one's sum + 1) before meeting recent zero.
    backSum contains consecutive one's sum after meeting recent zero.
    When meet zero, backSum is moved to frontSum.

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int frontSum = 0, backSum = 0, maxSum = 0;
            for (int n : nums) {
                if (n == 0) {
                    frontSum = backSum + 1;
                    backSum = 0;
                backSum += n;
                maxSum = Math.max(maxSum, frontSum + backSum);
            return maxSum;

Log in to reply

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