20240805 Finished

This commit is contained in:
jackfiled 2024-08-05 11:06:01 +08:00
parent 0a058a3277
commit 552f842be2
2 changed files with 53 additions and 1 deletions

View File

@ -195,3 +195,4 @@ mod p69_sqrtx;
mod p50_powx_n;
mod p149_max_points_on_a_line;
mod p70_climbing_stairs;
mod p198_house_robber;

View File

@ -0,0 +1,51 @@
/**
* [198] House Robber
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn rob(nums: Vec<i32>) -> i32 {
let n = nums.len();
let mut dp = Vec::with_capacity(n);
if n == 1 {
return nums[0];
}
let mut result = nums[0];
dp.push(result);
for i in 1..n {
let mut last = 0;
for j in 0..i - 1 {
last = last.max(dp[j]);
}
last = dp[i - 1].max(last + nums[i]);
dp.push(last);
result = result.max(last);
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_198() {
assert_eq!(4, Solution::rob(vec![1, 2, 3, 1]));
assert_eq!(12, Solution::rob(vec![2, 7, 9, 3, 1]));
assert_eq!(2, Solution::rob(vec![2, 1]));
assert_eq!(2, Solution::rob(vec![2]));
assert_eq!(4, Solution::rob(vec![2, 1, 1, 2]));
}
}