From ffa2553a3712b556c6d89ad1fcf3cd3b8da3d597 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 26 Apr 2025 15:22:38 +0800 Subject: [PATCH] 20250426 finished. --- src/problem/mod.rs | 3 +- ...p2444_count_subarrays_with_fixed_bounds.rs | 56 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 src/problem/p2444_count_subarrays_with_fixed_bounds.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 960d5c8..ca353ca 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -619,4 +619,5 @@ mod p2338_count_the_number_of_ideal_arrays; mod p2845_count_of_interesting_subarrays; -mod p1287_element_appearing_more_than_25_in_sorted_array; \ No newline at end of file +mod p1287_element_appearing_more_than_25_in_sorted_array; +mod p2444_count_subarrays_with_fixed_bounds; diff --git a/src/problem/p2444_count_subarrays_with_fixed_bounds.rs b/src/problem/p2444_count_subarrays_with_fixed_bounds.rs new file mode 100644 index 0000000..3d23528 --- /dev/null +++ b/src/problem/p2444_count_subarrays_with_fixed_bounds.rs @@ -0,0 +1,56 @@ +/** + * [2444] Count Subarrays With Fixed Bounds + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn count_subarrays(nums: Vec, min_k: i32, max_k: i32) -> i64 { + let mut result = 0; + let (mut border, mut last_min, mut last_max) = (None, None, None); + + for i in 0..nums.len() { + if nums[i] < min_k || nums[i] > max_k { + last_max = None; + last_min = None; + border = Some(i); + } + + if nums[i] == min_k { + last_min = Some(i); + } + + if nums[i] == max_k { + last_max = Some(i); + } + + if let Some(last_min) = last_min { + if let Some(last_max) = last_max { + let current = if let Some(border) = border { + last_min.min(last_max) - border + } else { + last_min.min(last_max) + 1 + }; + + result += current as i64 + } + } + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2444() { + assert_eq!(2, Solution::count_subarrays(vec![1, 3, 5, 2, 7, 5], 1, 5)); + assert_eq!(10, Solution::count_subarrays(vec![1, 1, 1, 1], 1, 1)); + } +}