Skip to content

Commit c2de333

Browse files
committed
Add problem 2844: Minimum Operations to Make a Special Number
1 parent 120eeba commit c2de333

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1988,6 +1988,7 @@ pub mod problem_2833_furthest_point_from_origin;
19881988
pub mod problem_2839_check_if_strings_can_be_made_equal_with_operations_i;
19891989
pub mod problem_2840_check_if_strings_can_be_made_equal_with_operations_ii;
19901990
pub mod problem_2841_maximum_sum_of_almost_unique_subarray;
1991+
pub mod problem_2844_minimum_operations_to_make_a_special_number;
19911992

19921993
#[cfg(test)]
19931994
mod test_utilities;
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn minimum_operations(num: String) -> i32 {
7+
let mut iter_1 = num.bytes().rev();
8+
9+
let mut result = iter_1.position(|d| d == b'0').map_or(num.len(), |i| {
10+
iter_1
11+
.position(|d| matches!(d, b'5' | b'0'))
12+
.map_or(num.len() - 1, |j| i + j)
13+
});
14+
15+
iter_1 = num.bytes().rev();
16+
17+
if let Some(operations) = iter_1
18+
.position(|d| d == b'5')
19+
.and_then(|i| iter_1.position(|d| matches!(d, b'2' | b'7')).map(|j| i + j))
20+
{
21+
result = result.min(operations);
22+
}
23+
24+
result as _
25+
}
26+
}
27+
28+
// ------------------------------------------------------ snip ------------------------------------------------------ //
29+
30+
impl super::Solution for Solution {
31+
fn minimum_operations(num: String) -> i32 {
32+
Self::minimum_operations(num)
33+
}
34+
}
35+
36+
#[cfg(test)]
37+
mod tests {
38+
#[test]
39+
fn test_solution() {
40+
super::super::tests::run::<super::Solution>();
41+
}
42+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod greedy;
2+
3+
pub trait Solution {
4+
fn minimum_operations(num: String) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [("2245047", 2), ("2908305", 3), ("10", 1)];
13+
14+
for (num, expected) in test_cases {
15+
assert_eq!(S::minimum_operations(num.to_string()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)