Skip to content

Commit bfa2125

Browse files
committed
Add problem 3196: Maximize Total Cost of Alternating Subarrays
1 parent c3e1271 commit bfa2125

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2132,6 +2132,7 @@ pub mod problem_3191_minimum_operations_to_make_binary_array_elements_equal_to_o
21322132
pub mod problem_3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii;
21332133
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;
2135+
pub mod problem_3196_maximize_total_cost_of_alternating_subarrays;
21352136
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21362137

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

0 commit comments

Comments
 (0)