Skip to content

Commit

Permalink
Add max consecutive ones
Browse files Browse the repository at this point in the history
  • Loading branch information
syohex committed Sep 21, 2021
1 parent fbde729 commit 822c664
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
8 changes: 8 additions & 0 deletions challenge/202109/max_consecutive_ones/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "max_consecutive_ones"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
33 changes: 33 additions & 0 deletions challenge/202109/max_consecutive_ones/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
let mut ret = 0;
let mut count = 0;
for (i, &num) in nums.iter().enumerate() {
if num == 1 {
count += 1;
}

if i == nums.len() - 1 || num == 0 {
ret = std::cmp::max(ret, count);
count = 0;
}
}
ret
}

fn main() {
let nums = vec![1, 1, 0, 1, 1, 1];
let ret = find_max_consecutive_ones(nums);
println!("ret={}", ret);
}

#[test]
fn test_find_max_consecutive_ones() {
{
let nums = vec![1, 1, 0, 1, 1, 1];
assert_eq!(find_max_consecutive_ones(nums), 3);
}
{
let nums = vec![1, 0, 1, 1, 0, 1];
assert_eq!(find_max_consecutive_ones(nums), 2);
}
}

0 comments on commit 822c664

Please sign in to comment.