Given a binary array, count the maximum number of consecutive 1s in it.

Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first and last two digits are consecutive 1s, so the maximum number of consecutive 1s is 3. Note: The input array contains only 0 and 1. The length of the input array is a positive integer and does not exceed 10,000.Copy the code

Link: leetcode-cn.com/problems/ma…

Train of thought: find the position of 1, then work backwards from that position until you find the position of 0. Stop and compare the maximum value.

    public int findMaxConsecutiveOnes(int[] nums) {
        int max = 0;
        int slow = 0;
        int num = 0;
        for(int i=0; i<nums.length;) {if(nums[i] == 1) {
                // Find the position that is not 1
                while(i<nums.length && nums[i] == 1) {
                    num++;
                    i++;
                }
                max = Math.max(max, num);
                num = 0;
                i += num+1;
            } else{ i++; }}return max;
    }
Copy the code