Java simple solution using sliding window


  • 0
    M

    Just going through the array, when finding 1 keep counting it and move the end pointer to the next element. O (n) Runtime: 9 ms

    public class Solution {
        
        public int findMaxConsecutiveOnes(int[] nums) {
            
            int end = 0;
            int max = 0;
            
            while (end < nums.length) {
                
                if (nums[end] == 1) {
                    int tmp = 1;
                    end++;
                    while (end < nums.length && nums[end] == 1) {
                        tmp++;
                        end++;
                    }
                    if (tmp > max) max = tmp;
                    continue;
                } 
                
                end++;
    
            }
             
            return max;   
        }
        
    }
    

Log in to reply
 

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