diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 2dd4b5b..4971920 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -362,3 +362,5 @@ mod p782_transform_to_chessboard; mod p1812_determine_color_of_a_chessboard_square; mod p935_knight_dialer; + +mod p2717_semi_ordered_permutation; diff --git a/src/problem/p2717_semi_ordered_permutation.rs b/src/problem/p2717_semi_ordered_permutation.rs new file mode 100644 index 0000000..172226d --- /dev/null +++ b/src/problem/p2717_semi_ordered_permutation.rs @@ -0,0 +1,45 @@ +/** + * [2717] Semi-Ordered Permutation + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn semi_ordered_permutation(nums: Vec) -> i32 { + let n = nums.len(); + + let one_pos = nums + .iter() + .enumerate() + .find_map(|(i, v)| if *v == 1 { Some(i) } else { None }) + .unwrap(); + let n_pos = nums + .iter() + .enumerate() + .find_map(|(i, v)| if *v == n as i32 { Some(i) } else { None }) + .unwrap(); + + let result = if one_pos < n_pos { + (n - 1 - n_pos) + (one_pos - 0) + } else { + (n - 1 - n_pos) + (one_pos - 0) - 1 + } as i32; + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2717() { + assert_eq!(2, Solution::semi_ordered_permutation(vec![2, 1, 4, 3])); + assert_eq!(3, Solution::semi_ordered_permutation(vec![2, 4, 1, 3])); + assert_eq!(0, Solution::semi_ordered_permutation(vec![1, 3, 4, 2, 5])); + } +}