20240418 Finished

This commit is contained in:
jackfiled 2024-04-18 11:24:59 +08:00
parent 65dd1924ed
commit 1fc3cd8e46
2 changed files with 42 additions and 1 deletions

View File

@ -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;
mod p134_gas_station;
mod p135_candy;

40
src/problem/p135_candy.rs Normal file
View File

@ -0,0 +1,40 @@
/**
* [135] Candy
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn candy(ratings: Vec<i32>) -> 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]));
}
}