[leetcode] (Array101) 485. Max Consecutive Ones

485. Max Consecutive Ones

https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3238/

Given a binary array nums, return the maximum number of consecutive 1's in the array.

 

 

Answers

mine

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        
        int curCount = 0;
        int maxCount = 0;
        
        for (int num : nums) {
            if (num == 1) {
                curCount++;
                maxCount = Math.max(curCount, maxCount);
            } else {
                curCount = 0;
            }
        }
        
        return maxCount;
        
    }
}

 

https://leetcode.com/problems/max-consecutive-ones/solutions/1507990/java-tc-o-n-sc-o-1-easy-concise-solution

/**
 * Maintain current count and maximum count so far.
 *
 * Time Complexity: O(N)
 *
 * Space Complexity: O(1)
 *
 * N = Length of the input array
 */
class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        if (nums == null) {
            throw new IllegalArgumentException("Input array is null");
        }

        int curCount = 0;
        int maxCount = 0;

        for (int n : nums) {
            if (n == 1) {
                curCount++;
                maxCount = Math.max(maxCount, curCount);
            } else {
                curCount = 0;
            }
        }

        return maxCount;
    }
}

 


Things I Learned

Validation check

Math.max(a, b)