Skip to content

Commit

Permalink
Add problem 1975: Maximum Matrix Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 30, 2023
1 parent 029d6cc commit c5e48cf
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
45 changes: 45 additions & 0 deletions src/problem_1975_maximum_matrix_sum/greedy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn max_matrix_sum(matrix: Vec<Vec<i32>>) -> 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<Vec<i32>>) -> i64 {
Self::max_matrix_sum(matrix)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
24 changes: 24 additions & 0 deletions src/problem_1975_maximum_matrix_sum/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
pub mod greedy;

pub trait Solution {
fn max_matrix_sum(matrix: Vec<Vec<i32>>) -> i64;
}

#[cfg(test)]
mod tests {
use super::Solution;
use crate::test_utilities::Matrix;

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit c5e48cf

Please sign in to comment.