From 87750598a382886c6c405b126c2dc087894fc615 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 29 Mar 2024 22:50:38 +0100 Subject: [PATCH] =?UTF-8?q?rs:=20add=20=C2=AB2962.=20Count=20Subarrays=20W?= =?UTF-8?q?here=20Max=20Element=20Appears=20at=20Least=20K=20Times=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...re-max-element-appears-at-least-k-times.rs | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 rs/count-subarrays-where-max-element-appears-at-least-k-times.rs diff --git a/rs/count-subarrays-where-max-element-appears-at-least-k-times.rs b/rs/count-subarrays-where-max-element-appears-at-least-k-times.rs new file mode 100644 index 0000000..fa9d46f --- /dev/null +++ b/rs/count-subarrays-where-max-element-appears-at-least-k-times.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn count_subarrays(nums: Vec, mut k: i32) -> i64 { + let m = *nums.iter().max().expect("1 ≤ nums.len() ≤ 10⁵"); + let mut counter: i64 = 0; + + let mut i: usize = 0; + for j in 0..nums.len() { + if nums[j] == m { + k -= 1; + } + + while k == 0 { + if nums[i] == m { + k += 1; + } + + i += 1; + } + + counter += i as i64; + } + + counter + } +}