BudiBadu Logo

Find Maximum Consecutive Ones

Array Easy 0 views
Like10

You are given a binary array consisting only of 0s and 1s. Your task is to determine the maximum number of consecutive 1s that appear in the array. Consecutive means that the 1s appear one after another without any 0s in between. The array may contain long sequences of 0s or 1s, and you need to count the longest run of continuous 1s.

Imagine the array as a series of light switches where 1 means the light is on and 0 means it is off. You want to find the longest stretch of time when the light stayed on without interruption. Each element in the array represents one moment in time. The goal is to track the longest sequence of “on” states before a “0” appears and breaks the streak.

The challenge encourages understanding of scanning sequences efficiently and keeping track of ongoing patterns within data. If there are no 1s in the array, the answer should be 0. If all numbers are 1s, the result is simply the length of the array.

Example 1:

Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The longest continuous sequence of 1s is three in a row.

Example 2:

Input: nums = [1,0,1,1,0,1]
Output: 2
Explanation: The longest sequence of 1s has length 2.

Example 3:

Input: nums = [0,0,0]
Output: 0
Explanation: There are no 1s in the array.

Algorithm Flow

Recommendation Algorithm Flow for Find Maximum Consecutive Ones - Budibadu
Recommendation Algorithm Flow for Find Maximum Consecutive Ones - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int find_maximum_consecutive_ones(Object input) {
        int[] nums = (int[]) input;
        int max_c = 0, cur = 0;
        for (int x : nums) {
            if (x == 1) { cur++; max_c = Math.max(max_c, cur); }
            else cur = 0;
        }
        return max_c;
    }
}