Very simple Java accepted solution - explained


  • 0
    M
    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            if(nums == null || nums.length == 0) {
                return 0;
            }
            
            int max = 0, first = 0, second = 0;
            
            for(int i = 0; i < nums.length; i++) {
                if(nums[i] == 0) {
                    // If zero, copy the count till now i.e., second into
                    // first. The reason we are doing +1 is that we should
                    // include the current zero
                    first = second + 1;
                    second = 0;
                } else {
                    second++; // Just keep incrementing second
                }
                max = Math.max(max, first + second);
            }
            return max;
        }
    }
    

Log in to reply
 

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