Skip to content

Commit cc025a4

Browse files
committed
Add problem 3206: Alternating Groups I
1 parent c9c00b0 commit cc025a4

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2135,6 +2135,7 @@ pub mod problem_3195_find_the_minimum_area_to_cover_all_ones_i;
21352135
pub mod problem_3196_maximize_total_cost_of_alternating_subarrays;
21362136
pub mod problem_3200_maximum_height_of_a_triangle;
21372137
pub mod problem_3201_find_the_maximum_length_of_valid_subsequence_i;
2138+
pub mod problem_3206_alternating_groups_i;
21382139
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21392140

21402141
#[cfg(test)]
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn number_of_alternating_groups(colors: Vec<i32>) -> i32 {
7+
assert!(colors.len() > 2);
8+
9+
let mut state = (colors[colors.len() - 2] << 1) | colors[colors.len() - 1];
10+
let mut result = 0;
11+
12+
for color in colors {
13+
state = (state << 1) | color;
14+
result += i32::from(matches!(state & 0b_111, 0b_010 | 0b_101));
15+
}
16+
17+
result
18+
}
19+
}
20+
21+
// ------------------------------------------------------ snip ------------------------------------------------------ //
22+
23+
impl super::Solution for Solution {
24+
fn number_of_alternating_groups(colors: Vec<i32>) -> i32 {
25+
Self::number_of_alternating_groups(colors)
26+
}
27+
}
28+
29+
#[cfg(test)]
30+
mod tests {
31+
#[test]
32+
fn test_solution() {
33+
super::super::tests::run::<super::Solution>();
34+
}
35+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn number_of_alternating_groups(colors: Vec<i32>) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [(&[1, 1, 1] as &[_], 0), (&[0, 1, 0, 0, 1], 3)];
13+
14+
for (colors, expected) in test_cases {
15+
assert_eq!(S::number_of_alternating_groups(colors.to_vec()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)