485. The maximum number of consecutive 1s-Java

Given a binary array, calculate the maximum number of consecutive 1s.

Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits and the last three digits are all consecutive 1, so the maximum number of consecutive 1s is 3.

Note: The
input array only contains 0 and 1.
The length of the input array is a positive integer and does not exceed 10,000.

Source: LeetCode
Link: https://leetcode-cn.com/problems/max-consecutive-ones

Method one: traverse once

Use a counter tmp to record the number of 1s, and another counter count to record the current maximum number of 1s.
When we encounter 1, tmp increases by one.
When it is not 1:
  Compare count with tmp, count records the larger value.
  Set tmp to 0.
  Return count.

public static int findMaxConsecutiveOnes(int[] nums) {
    
    
    int count = 0, tmp = 0;
    for (int num : nums) {
    
    
        if (num == 1) {
    
    
            tmp++;
        } else if (tmp > count) {
    
    
            count = tmp;
            tmp = 0;
        } else {
    
    
            tmp = 0;
        }
    }
    if (tmp > count) {
    
    
        count = tmp;
    }
    return count;
}

Guess you like

Origin blog.csdn.net/m0_46390568/article/details/107678369