20241021 finished.
This commit is contained in:
parent
c30e747bbc
commit
774d3c436e
|
@ -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 p3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii;
|
||||
mod p908_smallest_range_i;
|
||||
mod p910_smallest_range_ii;
|
43
src/problem/p910_smallest_range_ii.rs
Normal file
43
src/problem/p910_smallest_range_ii.rs
Normal 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));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user