Java Solution. No slicing window, no pointers. 9ms beats 92%


  • 0
    Z

    Basically, just loops through the array once and keeps track of the current maximum.

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int max = 0;  // save the maximum
            int count = 0; // save the count for the current consequence 1's
            int count2 = 0; // save the count for the previous consequence of 1's
            for (int n : nums) {
                if (n == 1) {
                    count++;
                } else {
                    max = Math.max(max, count + count2); //update max
                    count2 = count + 1; // "+1" for the flipped 0
                    count = 0;
                }
            }
            return Math.max(max, count + count2); // handle the last-index-edge case
        }
    }
    

Log in to reply
 

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