diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 978330d..dd6d8be 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -276,3 +276,5 @@ mod p983_minimum_cost_for_tickets; mod p997_find_the_town_judge; mod p3180_maximum_total_reward_using_operations_i; + +mod p3181_maximum_total_reward_using_operations_ii; diff --git a/src/problem/p3181_maximum_total_reward_using_operations_ii.rs b/src/problem/p3181_maximum_total_reward_using_operations_ii.rs new file mode 100644 index 0000000..d0f2fd2 --- /dev/null +++ b/src/problem/p3181_maximum_total_reward_using_operations_ii.rs @@ -0,0 +1,47 @@ +/** + * [3181] Maximum Total Reward Using Operations II + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn max_total_reward(reward_values: Vec) -> i32 { + let mut reward_values: Vec = reward_values.into_iter().map(|x| x as usize).collect(); + reward_values.sort_unstable(); + reward_values.dedup(); + + let max_value = *reward_values.last().unwrap(); + let n = reward_values.len(); + + if n >= 2 && max_value - 1 == reward_values[n - 2] { + return (2 * max_value - 1) as i32; + } + + let mut dp = vec![false; 2 * max_value + 1]; + dp[0] = true; + + unsafe { + for v in reward_values { + for i in (v..v << 1).rev() { + *(dp.get_unchecked_mut(i)) |= *dp.get_unchecked(i - v); + } + } + } + + dp.iter().enumerate().rfind(|(_, &x)| x).unwrap().0 as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3181() { + assert_eq!(4, Solution::max_total_reward(vec![1, 1, 3, 3])); + assert_eq!(11, Solution::max_total_reward(vec![1, 6, 4, 3, 2])); + } +}