Code Logo

Find Maximum Consecutive Ones

Published atDate not available
Easy 0 views
Like0

This problem feels like a little puzzle you can solve one step at a time. In Find Maximum Consecutive Ones, you are trying to work toward the right number by following one clear idea.

This problem hides a best streak, chain, or longest piece inside a larger list. You are not always taking everything. Instead, you are searching for the strongest run that still follows the rule. A choice that looks good right now may not always lead to the best final result, so careful thinking matters.

For example, if the input is nums = [0,0,0], the answer is 0. There are no 1s in the array. Another example is nums = [1,0,1,1,0,1], which gives 2. The longest sequence of 1s has length 2.

This is a friendly practice problem, but it still rewards careful reading. The key is to look for the best hidden streak, not just the first one that seems okay.

Example Input & Output

Example 1
Input
nums = [0,0,0]
Output
0
Explanation

There are no 1s in the array.

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 = [1,1,0,1,1,1]
Output
3
Explanation

The longest continuous sequence of 1s is three in a row.

Algorithm Flow

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

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;
    }
}