From c5e48cf8808a4bacad05d826d26dd5cca962229d Mon Sep 17 00:00:00 2001 From: EFanZh Date: Thu, 30 Nov 2023 22:45:14 +0800 Subject: [PATCH] Add problem 1975: Maximum Matrix Sum --- src/lib.rs | 1 + src/problem_1975_maximum_matrix_sum/greedy.rs | 45 +++++++++++++++++++ src/problem_1975_maximum_matrix_sum/mod.rs | 24 ++++++++++ 3 files changed, 70 insertions(+) create mode 100644 src/problem_1975_maximum_matrix_sum/greedy.rs create mode 100644 src/problem_1975_maximum_matrix_sum/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 9826b185..343567a1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1371,6 +1371,7 @@ pub mod problem_1967_number_of_strings_that_appear_as_substrings_in_word; pub mod problem_1968_array_with_elements_not_equal_to_average_of_neighbors; pub mod problem_1971_find_if_path_exists_in_graph; pub mod problem_1974_minimum_time_to_type_word_using_special_typewriter; +pub mod problem_1975_maximum_matrix_sum; pub mod problem_1979_find_greatest_common_divisor_of_array; #[cfg(test)] diff --git a/src/problem_1975_maximum_matrix_sum/greedy.rs b/src/problem_1975_maximum_matrix_sum/greedy.rs new file mode 100644 index 00000000..3f41b328 --- /dev/null +++ b/src/problem_1975_maximum_matrix_sum/greedy.rs @@ -0,0 +1,45 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn max_matrix_sum(matrix: Vec>) -> i64 { + let mut candidate_sum = 0_i64; + let mut min_abs = i32::MAX; + let mut has_odd_negatives = false; + + for row in matrix { + for mut value in row { + if value < 0 { + value = -value; + has_odd_negatives = !has_odd_negatives; + } + + candidate_sum += i64::from(value); + min_abs = min_abs.min(value); + } + } + + if has_odd_negatives { + candidate_sum -= i64::from(min_abs) * 2; + } + + candidate_sum + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn max_matrix_sum(matrix: Vec>) -> i64 { + Self::max_matrix_sum(matrix) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_1975_maximum_matrix_sum/mod.rs b/src/problem_1975_maximum_matrix_sum/mod.rs new file mode 100644 index 00000000..2d6585bc --- /dev/null +++ b/src/problem_1975_maximum_matrix_sum/mod.rs @@ -0,0 +1,24 @@ +pub mod greedy; + +pub trait Solution { + fn max_matrix_sum(matrix: Vec>) -> i64; +} + +#[cfg(test)] +mod tests { + use super::Solution; + use crate::test_utilities::Matrix; + + pub fn run() { + let test_cases = [ + (&[[1, -1], [-1, 1]] as &dyn Matrix<_>, 4), + (&[[1, 2, 3], [-1, -2, -3], [1, 2, 3]], 16), + (&[[-1, 0, -1], [-2, 1, 3], [3, 2, 2]], 15), + (&[[2, 9, 3], [5, 4, -4], [1, 7, 1]], 34), + ]; + + for (matrix, expected) in test_cases { + assert_eq!(S::max_matrix_sum(matrix.to_vec()), expected); + } + } +}