Skip to content

Commit 2b9f0b8

Browse files
committed
Add problem 3148: Maximum Difference Score in a Grid
1 parent f5ae39e commit 2b9f0b8

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2107,6 +2107,7 @@ pub mod problem_3142_check_if_grid_satisfies_conditions;
21072107
pub mod problem_3143_maximum_points_inside_the_square;
21082108
pub mod problem_3146_permutation_difference_between_two_strings;
21092109
pub mod problem_3147_taking_maximum_energy_from_the_mystic_dungeon;
2110+
pub mod problem_3148_maximum_difference_score_in_a_grid;
21102111
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21112112

21122113
#[cfg(test)]
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn max_score(grid: Vec<Vec<i32>>) -> i32 {
7+
let mut grid = grid;
8+
let mut iter = grid.iter_mut().map(Vec::as_mut_slice);
9+
let cache = iter.next().unwrap();
10+
11+
let mut result = cache
12+
.iter()
13+
.fold((i32::MIN, i32::MAX / 2), |(result, min), &value| {
14+
(result.max(value - min), min.min(value))
15+
})
16+
.0;
17+
18+
iter.for_each(|row| {
19+
let mut left = i32::MAX;
20+
21+
cache.iter_mut().zip(&*row).for_each(|(target, &value)| {
22+
result = result.max(value - left.min(*target));
23+
*target = (*target).min(value);
24+
left = left.min(*target);
25+
});
26+
});
27+
28+
result
29+
}
30+
}
31+
32+
// ------------------------------------------------------ snip ------------------------------------------------------ //
33+
34+
impl super::Solution for Solution {
35+
fn max_score(grid: Vec<Vec<i32>>) -> i32 {
36+
Self::max_score(grid)
37+
}
38+
}
39+
40+
#[cfg(test)]
41+
mod tests {
42+
#[test]
43+
fn test_solution() {
44+
super::super::tests::run::<super::Solution>();
45+
}
46+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
pub mod dynamic_programming;
2+
3+
pub trait Solution {
4+
fn max_score(grid: 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+
(
15+
&[[9, 5, 7, 3], [8, 9, 6, 1], [6, 7, 14, 3], [2, 5, 3, 1]] as &dyn Matrix<_>,
16+
9,
17+
),
18+
(&[[4, 3, 2], [3, 2, 1]], -1),
19+
(&[[4, 9], [5, 2], [3, 1]], 5),
20+
];
21+
22+
for (grid, expected) in test_cases {
23+
assert_eq!(S::max_score(grid.to_vec()), expected);
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)