Skip to content

Commit

Permalink
Add problem 1937: Maximum Number of Points with Cost
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed May 19, 2024
1 parent 107e160 commit 17f942b
Show file tree
Hide file tree
Showing 3 changed files with 72 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 @@ -1434,6 +1434,7 @@ pub mod problem_1929_concatenation_of_array;
pub mod problem_1930_unique_length_3_palindromic_subsequences;
pub mod problem_1935_maximum_number_of_words_you_can_type;
pub mod problem_1936_add_minimum_number_of_rungs;
pub mod problem_1937_maximum_number_of_points_with_cost;
pub mod problem_1941_check_if_all_characters_have_equal_number_of_occurrences;
pub mod problem_1944_number_of_visible_people_in_a_queue;
pub mod problem_1945_sum_of_digits_of_string_after_convert;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
pub struct Solution;

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

use std::mem;

impl Solution {
pub fn max_points(points: Vec<Vec<i32>>) -> i64 {
let columns = points.first().map_or(0, Vec::len);
let mut buffer = vec![0_u64; columns * 2].into_boxed_slice();
let (mut cache, mut temp) = buffer.split_at_mut(columns);

for row in points {
let mut left_max = 0;

for (i, (target, &top)) in (0..).zip(temp.iter_mut().zip(&*cache)) {
left_max = left_max.max(top + i);
*target = left_max - i;
}

let mut right_max = 0;

for (i, ((target, &top), &value)) in (0..).zip(temp.iter_mut().zip(&*cache).zip(&row).rev()) {
right_max = right_max.max(top + i);
*target = (*target).max(right_max - i) + u64::from(value as u32);
}

mem::swap(&mut cache, &mut temp);
}

cache.iter().copied().max().unwrap() as _
}
}

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

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

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

pub trait Solution {
fn max_points(points: 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, 2, 3], [1, 5, 1], [3, 1, 1]] as &dyn Matrix<_>, 9),
(&[[1, 5], [2, 3], [4, 2]], 11),
];

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

0 comments on commit 17f942b

Please sign in to comment.