Max Consecutive Ones In One Pass

Track the current run length and the best run so far in a single loop, resetting the run whenever a zero breaks the streak.

RustData Integrity

Code

rustsnippet
21 lines
fn max_consecutive_ones(nums: &[u8]) -> usize {
    // Single pass: track the current run length and the best run so far
    let (mut run, mut best) = (0usize, 0usize);
    for &bit in nums {
        if bit == 1 {
            run += 1;
            if run > best {
                best = run;
            }
        } else {
            run = 0;
        }
    }
    best
}

fn main() {
    println!("{}", max_consecutive_ones(&[1, 1, 0, 1, 1, 1]));
    println!("{}", max_consecutive_ones(&[1, 0, 1, 1, 0, 1]));
    println!("{}", max_consecutive_ones(&[0, 0, 0]));
}

How the code behaves

Max Consecutive Ones In One Pass reduces to the functions max_consecutive_ones and main.

One loop does the cycling here: for &bit in nums.

What to watch for

  • The package manager never enters the picture for this snippet.

Using it

The entry-point signature is fn max_consecutive_ones(nums: &[u8]) -> usize

main calls 1 helper in sequence: max_consecutive_ones.

Key statements

let (mut run, mut best) = (0usize, 0usize);

Interactive Tools for This Topic

FAQ

How do you run Max Consecutive Ones In One Pass?
Direct execution is enough; the script has no external requirements.