Skip to content

Commit

Permalink
Add problem 2302: Count Subarrays With Score Less Than K
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 1, 2024
1 parent 5a19d5f commit 31539c0
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1709,6 +1709,7 @@ pub mod problem_2294_partition_array_such_that_maximum_difference_is_k;
pub mod problem_2295_replace_elements_in_an_array;
pub mod problem_2299_strong_password_checker_ii;
pub mod problem_2300_successful_pairs_of_spells_and_potions;
pub mod problem_2302_count_subarrays_with_score_less_than_k;

#[cfg(test)]
mod test_utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn count_subarrays(nums: Vec<i32>, k: i64) -> i64 {
let k = k as u64;
let mut start = 0;
let mut sum = 0;

(1..).zip(&nums).fold(0, |result, (end, &num)| {
sum += u64::from(num as u32);

while sum * (end - start) >= k {
sum -= u64::from(nums[start as usize] as u32);
start += 1;
}

result + end - start
}) as _
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn count_subarrays(nums: Vec<i32>, k: i64) -> i64 {
Self::count_subarrays(nums, k)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_2302_count_subarrays_with_score_less_than_k/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod iterative;

pub trait Solution {
fn count_subarrays(nums: Vec<i32>, k: i64) -> i64;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [((&[2, 1, 4, 3, 5] as &[_], 10), 6), ((&[1, 1, 1], 5), 5)];

for ((nums, k), expected) in test_cases {
assert_eq!(S::count_subarrays(nums.to_vec(), k), expected);
}
}
}

0 comments on commit 31539c0

Please sign in to comment.