diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 4e7642e..470f9e1 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -104,4 +104,5 @@ mod p45_jump_game_ii; mod p274_h_index; mod p380_insert_delete_getrandom_o1; mod p238_product_of_array_except_self; -mod p134_gas_station; \ No newline at end of file +mod p134_gas_station; +mod p135_candy; \ No newline at end of file diff --git a/src/problem/p135_candy.rs b/src/problem/p135_candy.rs new file mode 100644 index 0000000..7d6ce6e --- /dev/null +++ b/src/problem/p135_candy.rs @@ -0,0 +1,40 @@ +/** + * [135] Candy + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn candy(ratings: Vec) -> i32 { + let n = ratings.len(); + let mut children = vec![1; n]; + + for i in 1..n { + if ratings[i] > ratings[i - 1] { + children[i] = children[i].max(children[i - 1] + 1); + } + } + + for i in (0..n - 1).rev() { + if ratings[i] > ratings[i + 1] { + children[i] = children[i].max(children[i + 1] + 1); + } + } + + children.iter().sum() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_135() { + assert_eq!(5, Solution::candy(vec![1, 0, 2])); + assert_eq!(4, Solution::candy(vec![1, 2, 2])); + } +}