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.
Code
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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Max Consecutive Ones In One Pass?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.