Java use subtraction instead of sum up

  • 0

    As the element of array is either 1 or 0, we can reduce the sum up calculation by doing subtraction between any two '0's. The line outside of while loop is to make sure the code covers the situation where last element's value is 0.

        public int findMaxConsecutiveOnes(int[] nums) {
            int sum = 0;
            int prevZ = -1, i = 0;
            while(i < nums.length){
                if(nums[i] == 0){
                    sum = Math.max(i-prevZ-1, sum);
                    prevZ = i;
            sum = Math.max(sum, nums.length-prevZ-1);
            return sum;

Log in to reply

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