BudiBadu Logo

Find Maximum Consecutive Ones

Array Easy 5 views
Like10

Imagine you're reviewing a digital sensor feed represented as a sequence of 0s and 1s. A "1" means a signal is active, while a "0" means it's silent. Your mission in Find Maximum Consecutive Ones is to find the longest uninterrupted stretch of 1s in the array. This helps identify the longest peak "up-time" for the network!

The "secret sauce" is a Linear Counter. You walk through the array once and track two things: your current "streak" of 1s and the "max" streak found so far. Every time you hit a 1, your current streak grows. or if you hit a 0, it resets. By comparing your current streak to the max at each step, you find the record-setting duration in a single O(n) pass. It’s an elegant, fast, and simple solution that provides the exact "peak duration" for the analysts without wasting memory at all!

When the task involves connectivity or route cost, build adjacency carefully and guard against revisiting stale states. Use a visited or best-distance structure to avoid repeated work, and ensure unreachable scenarios return the required fallback value instead of partial traversal results.

Examples

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