Skip to content

Commit 51e9798

Browse files
committed
Add problem 2679: Sum in a Matrix
1 parent dfd3225 commit 51e9798

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
@@ -1938,6 +1938,7 @@ pub mod problem_2670_find_the_distinct_difference_array;
19381938
pub mod problem_2671_frequency_tracker;
19391939
pub mod problem_2673_make_costs_of_paths_equal_in_a_binary_tree;
19401940
pub mod problem_2678_number_of_senior_citizens;
1941+
pub mod problem_2679_sum_in_a_matrix;
19411942

19421943
#[cfg(test)]
19431944
mod test_utilities;
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn matrix_sum(nums: Vec<Vec<i32>>) -> i32 {
7+
let mut nums = nums;
8+
9+
for num in &mut nums {
10+
num.sort_unstable_by(|&lhs, &rhs| u32::cmp(&(rhs as _), &(lhs as _)));
11+
}
12+
13+
(0..nums.first().map_or(0, Vec::len))
14+
.map(|column| {
15+
nums.iter()
16+
.map_while(|row| row.get(column).copied())
17+
.fold(0, |max, value| u32::max(max, value as _))
18+
})
19+
.sum::<u32>() as _
20+
}
21+
}
22+
23+
// ------------------------------------------------------ snip ------------------------------------------------------ //
24+
25+
impl super::Solution for Solution {
26+
fn matrix_sum(nums: Vec<Vec<i32>>) -> i32 {
27+
Self::matrix_sum(nums)
28+
}
29+
}
30+
31+
#[cfg(test)]
32+
mod tests {
33+
#[test]
34+
fn test_solution() {
35+
super::super::tests::run::<super::Solution>();
36+
}
37+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn matrix_sum(nums: Vec<Vec<i32>>) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
use crate::test_utilities::Matrix;
11+
12+
pub fn run<S: Solution>() {
13+
let test_cases = [
14+
(&[[7, 2, 1], [6, 4, 2], [6, 5, 3], [3, 2, 1]] as &dyn Matrix<_>, 15),
15+
(&[[1]], 1),
16+
];
17+
18+
for (nums, expected) in test_cases {
19+
assert_eq!(S::matrix_sum(nums.to_vec()), expected);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)