20241021 finished.

This commit is contained in:
jackfiled 2024-10-21 16:16:25 +08:00
parent c30e747bbc
commit 774d3c436e
2 changed files with 45 additions and 1 deletions

View File

@ -270,3 +270,4 @@ mod p3193_count_the_number_of_inversions;
mod p3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i; 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 p3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii;
mod p908_smallest_range_i; mod p908_smallest_range_i;
mod p910_smallest_range_ii;

View File

@ -0,0 +1,43 @@
/**
* [910] Smallest Range II
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn smallest_range_ii(nums: Vec<i32>, 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));
}
}