Java O(n) Easy To Understand Solution

  • 1

    For this question, we keep track of two variables: max, count. As we iterate through the elements of nums, count will keep track of the number of consecutive 1s. When count becomes greater than max, we update our max to the value of count.

    We reset count back to 0 when we encounter a 0, and increment by 1 when we encounter a 1.

    Time Complexity
    The time complexity is O(n) where n is the number of elements in nums, since we iterate through all elements in nums.

    class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int max = 0;
            int count = 0;
           // Iterate through all contents of num, updating count, max
            for (int num : nums) {
                if (num == 1) {
                    count += 1;
                } else {
                    count = 0;
                max = Math.max(max, count);
            return max;

Log in to reply

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