-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
32 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
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 |
---|---|---|
|
@@ -157,3 +157,4 @@ mod smallest_letter; | |
mod negative_numbers; | ||
mod guess_number; | ||
mod merge_nodes; | ||
mod subarray_sum; |
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,30 @@ | ||
pub fn min_sub_array_len(target: i32, numbers: Vec<i32>) -> i32 { | ||
let (mut left, mut right) = (0, 0); | ||
let mut sum = 0; | ||
let mut min_len = usize::MAX; | ||
while right < numbers.len() { | ||
sum += numbers[right]; | ||
right += 1; | ||
|
||
while sum >= target { | ||
min_len = std::cmp::min(min_len, right - left); | ||
sum -= numbers[left]; | ||
left += 1; | ||
} | ||
} | ||
|
||
match min_len == usize::MAX { | ||
true => 0, | ||
false => min_len as i32, | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn finds_length_of_smallest_subarr_that_sums_to_target() { | ||
assert_eq!(2, min_sub_array_len(7, vec![2, 3, 1, 2, 4, 3])) | ||
} | ||
} |