From 774d3c436eb0fa6a8ab872248b0c065e0f888f7c Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 21 Oct 2024 16:16:25 +0800 Subject: [PATCH] 20241021 finished. --- src/problem/mod.rs | 3 +- src/problem/p910_smallest_range_ii.rs | 43 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 src/problem/p910_smallest_range_ii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index e609c9c..f9d420d 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -269,4 +269,5 @@ mod p3194_minimum_average_of_smallest_and_largest_elements; mod p3193_count_the_number_of_inversions; mod p3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i; mod p3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii; -mod p908_smallest_range_i; \ No newline at end of file +mod p908_smallest_range_i; +mod p910_smallest_range_ii; \ No newline at end of file diff --git a/src/problem/p910_smallest_range_ii.rs b/src/problem/p910_smallest_range_ii.rs new file mode 100644 index 0000000..de38376 --- /dev/null +++ b/src/problem/p910_smallest_range_ii.rs @@ -0,0 +1,43 @@ +/** + * [910] Smallest Range II + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn smallest_range_ii(nums: Vec, k: i32) -> i32 { + let mut nums = nums; + nums.sort(); + + let mut min = *nums.first().unwrap(); + let mut max = *nums.last().unwrap(); + let mut result = max - min; + + for i in 1..nums.len() { + let m = (max - k).max(nums[i - 1] + k); + let n = (min + k).min(nums[i] - k); + + result = result.min((m - n).abs()); + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_910() { + assert_eq!(3, Solution::smallest_range_ii(vec![1, 4, 6, 4], 3)); + assert_eq!(3, Solution::smallest_range_ii(vec![4, 7, 4], 4)); + assert_eq!(0, Solution::smallest_range_ii(vec![1], 0)); + assert_eq!(6, Solution::smallest_range_ii(vec![0, 10], 2)); + assert_eq!(3, Solution::smallest_range_ii(vec![1, 3, 6], 3)); + } +}