Skip to content

Commit

Permalink
Add problem 0670: Maximum Swap
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Jun 7, 2024
1 parent 0f7d0b9 commit abd2eff
Show file tree
Hide file tree
Showing 3 changed files with 79 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 @@ -375,6 +375,7 @@ pub mod problem_0650_2_keys_keyboard;
pub mod problem_0653_two_sum_iv_input_is_a_bst;
pub mod problem_0654_maximum_binary_tree;
pub mod problem_0665_non_decreasing_array;
pub mod problem_0670_maximum_swap;
pub mod problem_0673_number_of_longest_increasing_subsequence;
pub mod problem_0674_longest_continuous_increasing_subsequence;
pub mod problem_0677_map_sum_pairs;
Expand Down
43 changes: 43 additions & 0 deletions src/problem_0670_maximum_swap/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
pub struct Solution;

use std::collections::HashMap;

impl Solution {
pub fn maximum_swap(num: i32) -> i32 {
let mut nums = Vec::new();
let mut map = HashMap::new();
let mut num = num;
while num != 0 {
let digit = num % 10;
map.entry(digit).or_insert_with(|| nums.len());
nums.push(digit);
num /= 10;
}

let mut nums_sorted = nums.clone();
nums_sorted.sort_unstable();

for idx in (0..nums.len()).rev() {
if nums[idx] < nums_sorted[idx] {
nums.swap(idx, map[&nums_sorted[idx]]);
break;
}
}

nums.into_iter().rev().fold(0, |acc, x| acc * 10 + x)
}
}

impl super::Solution for Solution {
fn maximum_swap(num: i32) -> i32 {
Self::maximum_swap(num)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
35 changes: 35 additions & 0 deletions src/problem_0670_maximum_swap/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
pub mod iterative;

pub trait Solution {
fn maximum_swap(num: i32) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(0, 0),
(1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5),
(6, 6),
(7, 7),
(8, 8),
(9, 9),
(10, 10),
(11, 11),
(12, 21),
(13, 31),
(2736, 7236),
(9973, 9973),
];

for (num, expected) in test_cases {
assert_eq!(S::maximum_swap(num), expected);
}
}
}

0 comments on commit abd2eff

Please sign in to comment.