Skip to content

Commit c9c00b0

Browse files
committed
Add problem 3201: Find the Maximum Length of Valid Subsequence I
1 parent 86b46a7 commit c9c00b0

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2134,6 +2134,7 @@ pub mod problem_3194_minimum_average_of_smallest_and_largest_elements;
21342134
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;
2137+
pub mod problem_3201_find_the_maximum_length_of_valid_subsequence_i;
21372138
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21382139

21392140
#[cfg(test)]
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn maximum_length(nums: Vec<i32>) -> i32 {
7+
let mut max_even = 0;
8+
let mut max_odd = 0;
9+
let mut max_alt_even = 0;
10+
let mut max_alt_odd = 0;
11+
12+
for num in nums {
13+
(max_even, max_odd, max_alt_even, max_alt_odd) = if num & 1 == 0 {
14+
(max_even + 1, max_odd, max_alt_even.max(max_alt_odd + 1), max_alt_odd)
15+
} else {
16+
(max_even, max_odd + 1, max_alt_even, max_alt_odd.max(max_alt_even + 1))
17+
}
18+
}
19+
20+
max_even.max(max_odd).max(max_alt_even).max(max_alt_odd)
21+
}
22+
}
23+
24+
// ------------------------------------------------------ snip ------------------------------------------------------ //
25+
26+
impl super::Solution for Solution {
27+
fn maximum_length(nums: Vec<i32>) -> i32 {
28+
Self::maximum_length(nums)
29+
}
30+
}
31+
32+
#[cfg(test)]
33+
mod tests {
34+
#[test]
35+
fn test_solution() {
36+
super::super::tests::run::<super::Solution>();
37+
}
38+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
pub mod dynamic_programming;
2+
3+
pub trait Solution {
4+
fn maximum_length(nums: 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 = [
13+
(&[1, 2, 3, 4] as &[_], 4),
14+
(&[1, 2, 1, 1, 2, 1, 2], 6),
15+
(&[1, 3], 2),
16+
(&[2, 7, 7, 7, 8], 3),
17+
];
18+
19+
for (nums, expected) in test_cases {
20+
assert_eq!(S::maximum_length(nums.to_vec()), expected);
21+
}
22+
}
23+
}

0 commit comments

Comments
 (0)