Skip to content

Commit

Permalink
Add problem 1770: Maximum Score from Performing Multiplication Operat…
Browse files Browse the repository at this point in the history
…ions
  • Loading branch information
EFanZh committed Feb 12, 2024
1 parent a0aef22 commit b8fb2e8
Show file tree
Hide file tree
Showing 3 changed files with 62 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 @@ -1321,6 +1321,7 @@ pub mod problem_1764_form_array_by_concatenating_subarrays_of_another_array;
pub mod problem_1765_map_of_highest_peak;
pub mod problem_1768_merge_strings_alternately;
pub mod problem_1769_minimum_number_of_operations_to_move_all_balls_to_each_box;
pub mod problem_1770_maximum_score_from_performing_multiplication_operations;
pub mod problem_1773_count_items_matching_a_rule;
pub mod problem_1774_closest_dessert_cost;
pub mod problem_1775_equal_sum_arrays_with_minimum_number_of_operations;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
pub struct Solution;

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

impl Solution {
pub fn maximum_score(nums: Vec<i32>, multipliers: Vec<i32>) -> i32 {
let n = nums.len();
let m = multipliers.len();
let mut cache = vec![0; m + 1].into_boxed_slice();

for (length, &multiplier) in (n - m + 1..).zip(multipliers.iter().rev()) {
let mut iter = cache[..=n + 1 - length].iter_mut();
let mut target = iter.next().unwrap();

for (start, top_right) in iter.enumerate() {
*target = (*target + nums[start + length - 1] * multiplier).max(*top_right + nums[start] * multiplier);

target = top_right;
}
}

cache[0]
}
}

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

impl super::Solution for Solution {
fn maximum_score(nums: Vec<i32>, multipliers: Vec<i32>) -> i32 {
Self::maximum_score(nums, multipliers)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
pub mod dynamic_programming;

pub trait Solution {
fn maximum_score(nums: Vec<i32>, multipliers: Vec<i32>) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [
((&[1, 2, 3] as &[_], &[3, 2, 1] as &[_]), 14),
((&[-5, -3, -3, -2, 7, 1], &[-10, -5, 3, 4, 6]), 102),
];

for ((nums, multipliers), expected) in test_cases {
assert_eq!(S::maximum_score(nums.to_vec(), multipliers.to_vec()), expected);
}
}
}

0 comments on commit b8fb2e8

Please sign in to comment.