Skip to content

Commit 554de6b

Browse files
committed
Add problem 3035: Maximum Palindromes After Operations
1 parent 2976f73 commit 554de6b

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2055,6 +2055,7 @@ pub mod problem_3024_type_of_triangle;
20552055
pub mod problem_3026_maximum_good_subarray_sum;
20562056
pub mod problem_3028_ant_on_the_boundary;
20572057
pub mod problem_3033_modify_the_matrix;
2058+
pub mod problem_3035_maximum_palindromes_after_operations;
20582059

20592060
#[cfg(test)]
20602061
mod test_utilities;
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn max_palindromes_after_operations(words: Vec<String>) -> i32 {
7+
let mut counts = [0_u32; 26];
8+
9+
let mut word_lengths = words
10+
.into_iter()
11+
.map(|word| {
12+
for c in word.bytes() {
13+
counts[usize::from(c) - usize::from(b'a')] += 1;
14+
}
15+
16+
word.len() as u16
17+
})
18+
.collect::<Vec<_>>();
19+
20+
let mut even_pairs = 0;
21+
22+
for count in counts {
23+
even_pairs += (count / 2) as u16;
24+
}
25+
26+
word_lengths.sort_unstable();
27+
28+
word_lengths
29+
.iter()
30+
.take_while(|&&length| {
31+
let required_even_pairs = length / 2;
32+
33+
if even_pairs < required_even_pairs {
34+
false
35+
} else {
36+
even_pairs -= required_even_pairs;
37+
38+
true
39+
}
40+
})
41+
.count() as _
42+
}
43+
}
44+
45+
// ------------------------------------------------------ snip ------------------------------------------------------ //
46+
47+
impl super::Solution for Solution {
48+
fn max_palindromes_after_operations(words: Vec<String>) -> i32 {
49+
Self::max_palindromes_after_operations(words)
50+
}
51+
}
52+
53+
#[cfg(test)]
54+
mod tests {
55+
#[test]
56+
fn test_solution() {
57+
super::super::tests::run::<super::Solution>();
58+
}
59+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
pub mod greedy;
2+
3+
pub trait Solution {
4+
fn max_palindromes_after_operations(words: Vec<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 = [
13+
(&["abbb", "ba", "aa"] as &[_], 3),
14+
(&["abc", "ab"], 2),
15+
(&["cd", "ef", "a"], 1),
16+
];
17+
18+
for (words, expected) in test_cases {
19+
assert_eq!(
20+
S::max_palindromes_after_operations(words.iter().copied().map(str::to_string).collect()),
21+
expected,
22+
);
23+
}
24+
}
25+
}

0 commit comments

Comments
 (0)