-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 2302: Count Subarrays With Score Less Than K
- Loading branch information
Showing
3 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 38 additions & 0 deletions
38
src/problem_2302_count_subarrays_with_score_less_than_k/iterative.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
18
src/problem_2302_count_subarrays_with_score_less_than_k/mod.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |