Skip to content

Commit

Permalink
Add problem 2017: Grid Game
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jun 11, 2024
1 parent 48683fc commit 0739097
Show file tree
Hide file tree
Showing 3 changed files with 63 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 @@ -1478,6 +1478,7 @@ pub mod problem_2007_find_original_array_from_doubled_array;
pub mod problem_2011_final_value_of_variable_after_performing_operations;
pub mod problem_2012_sum_of_beauty_in_the_array;
pub mod problem_2016_maximum_difference_between_increasing_elements;
pub mod problem_2017_grid_game;
pub mod problem_2022_convert_1d_array_into_2d_array;
pub mod problem_2024_maximize_the_confusion_of_an_exam;
pub mod problem_2027_minimum_moves_to_convert_string;
Expand Down
39 changes: 39 additions & 0 deletions src/problem_2017_grid_game/greedy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
pub struct Solution;

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

use std::convert::TryInto;

impl Solution {
pub fn grid_game(grid: Vec<Vec<i32>>) -> i64 {
let [first_row, second_row]: &[_; 2] = grid.as_slice().try_into().ok().unwrap();
let first_row_sum = first_row.iter().fold(0_u64, |sum, &x| sum + u64::from(x as u32));
let mut result = u64::MAX;
let mut top_sum = 0_u64;
let mut bottom_sum = 0_u64;

for (&top, &bottom) in first_row.iter().zip(second_row) {
top_sum += u64::from(top as u32);
result = result.min(bottom_sum.max(first_row_sum - top_sum));
bottom_sum += u64::from(bottom as u32);
}

result as _
}
}

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

impl super::Solution for Solution {
fn grid_game(grid: Vec<Vec<i32>>) -> i64 {
Self::grid_game(grid)
}
}

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

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

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

pub fn run<S: Solution>() {
let test_cases = [
(&[[2, 5, 4], [1, 5, 1]] as &dyn Matrix<_>, 4),
(&[[3, 3, 1], [8, 5, 2]], 4),
(&[[1, 3, 1, 15], [1, 3, 3, 1]], 7),
];

for (grid, expected) in test_cases {
assert_eq!(S::grid_game(grid.to_vec()), expected);
}
}
}

0 comments on commit 0739097

Please sign in to comment.