This article is participating in the “Java Theme Month – Java Brush questions punch card”, see the activity link for details

Topic describes

This is 485 on LeetCode. The maximum number of consecutive 1s.

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

Example:

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

Tip:

  • The input array contains only zeros and ones.
  • The length of the input array is a positive integer and does not exceed 10,000.

Double pointer

Use I and j to represent the left and right boundaries of continuous 1, respectively.

The initial state I == j, when I reaches the first 1, let j keep moving to the right until it reaches the right boundary.

Update the ans

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int n = nums.length;
        int ans = 0;
        for (int i = 0, j = 0; i < n; j = i) {
            if (nums[i] == 1) {
                while (j + 1 < n && nums[j + 1] = =1) j++;
                ans = Math.max(ans, j - i + 1);
                i = j + 1;
            } else{ i++; }}returnans; }}Copy the code
  • Time complexity: O(n)O(n)O(n)
  • Space complexity: O(1)O(1)O(1)

The last

This is the No.* of our “Brush through LeetCode” series, which started on 2021/01/01. There are 1916 topics on LeetCode as of the start date, some of which have locks.

In this series of articles, in addition to explaining how to solve the problem, I will also present the most concise code possible. If a general solution is involved, the corresponding code template will also be used.

As the number of LeetCode questions keeps increasing with weekly and biweekly competitions, in order to facilitate our progress statistics, we will calculate the progress according to the total number of questions at the beginning of the series as the denominator and the completed questions as the numerator. Current progress is */1916.

In order to facilitate students to debug and submit codes on computers, I have set up a relevant warehouse on Github: github.com/SharingSour…

In the repository, you’ll see links to the series, the corresponding code for the series, the LeetCode source links, and some other preferred solutions.