Skip to content

Commit f5ae39e

Browse files
committed
Add problem 3147: Taking Maximum Energy From the Mystic Dungeon
1 parent e47511c commit f5ae39e

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2106,6 +2106,7 @@ pub mod problem_3138_minimum_length_of_anagram_concatenation;
21062106
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;
2109+
pub mod problem_3147_taking_maximum_energy_from_the_mystic_dungeon;
21092110
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21102111

21112112
#[cfg(test)]
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod suffix_sums;
2+
3+
pub trait Solution {
4+
fn maximum_energy(energy: Vec<i32>, k: i32) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [((&[5, 2, -10, -5, 1] as &[_], 3), 3), ((&[-2, -3, -1], 2), -1)];
13+
14+
for ((energy, k), expected) in test_cases {
15+
assert_eq!(S::maximum_energy(energy.to_vec(), k), expected);
16+
}
17+
}
18+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
use std::cell::Cell;
6+
7+
impl Solution {
8+
pub fn maximum_energy(energy: Vec<i32>, k: i32) -> i32 {
9+
let mut energy = energy;
10+
let slice = energy.as_mut_slice();
11+
let cell_slice = Cell::from_mut(slice).as_slice_of_cells();
12+
13+
cell_slice
14+
.windows(k.cast_unsigned() as usize + 1)
15+
.rev()
16+
.for_each(|window| {
17+
let first = window.first().unwrap();
18+
let last = window.last().unwrap();
19+
20+
first.set(first.get() + last.get());
21+
});
22+
23+
slice.iter().copied().fold(i32::MIN, i32::max)
24+
}
25+
}
26+
27+
// ------------------------------------------------------ snip ------------------------------------------------------ //
28+
29+
impl super::Solution for Solution {
30+
fn maximum_energy(energy: Vec<i32>, k: i32) -> i32 {
31+
Self::maximum_energy(energy, k)
32+
}
33+
}
34+
35+
#[cfg(test)]
36+
mod tests {
37+
#[test]
38+
fn test_solution() {
39+
super::super::tests::run::<super::Solution>();
40+
}
41+
}

0 commit comments

Comments
 (0)