Skip to content

Commit

Permalink
Add problem 0605: Can Place Flowers
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Jun 22, 2024
1 parent 431a742 commit 06b354b
Show file tree
Hide file tree
Showing 3 changed files with 63 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 @@ -372,6 +372,7 @@ pub mod problem_0581_shortest_unsorted_continuous_subarray;
pub mod problem_0594_longest_harmonious_subsequence;
pub mod problem_0598_range_addition_ii;
pub mod problem_0599_minimum_index_sum_of_two_lists;
pub mod problem_0605_can_place_flowers;
pub mod problem_0606_construct_string_from_binary_tree;
pub mod problem_0623_add_one_row_to_tree;
pub mod problem_0640_solve_the_equation;
Expand Down
38 changes: 38 additions & 0 deletions src/problem_0605_can_place_flowers/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pub struct Solution;

impl Solution {
pub fn can_place_flowers(flowerbed: Vec<i32>, n: i32) -> bool {
let mut can = 0;
let mut prev_idx = None;
for idx in flowerbed
.into_iter()
.chain([0, 1])
.enumerate()
.filter_map(|(idx, bed)| (bed == 1).then_some(idx as i32))
{
if can >= n {
return true;
}
let size = prev_idx.map_or_else(|| idx - 1, |prev| idx - prev - 3);
if size > 0 {
can += (size + 1) / 2;
}
prev_idx = Some(idx);
}
can >= n
}
}

impl super::Solution for Solution {
fn can_place_flowers(flowerbed: Vec<i32>, n: i32) -> bool {
Self::can_place_flowers(flowerbed, n)
}
}

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

pub trait Solution {
fn can_place_flowers(flowerbed: Vec<i32>, n: i32) -> bool;
}

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

pub fn run<S: Solution>() {
let test_cases = [
((&[1, 0, 0, 0, 1] as &[_], 1), true),
((&[1, 0, 0, 0, 1], 2), false),
((&[0, 0, 1, 0, 1], 1), true),
((&[1, 0, 0, 0, 1, 0, 0], 2), true),
((&[1, 0, 0, 0, 1], 0), true),
];

for ((flowerbed, n), expected) in test_cases {
assert_eq!(S::can_place_flowers(flowerbed.to_vec(), n), expected);
}
}
}

0 comments on commit 06b354b

Please sign in to comment.