diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 8903cc1..e3d12ea 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -194,4 +194,5 @@ mod p172_factorial_trailing_zeroes; mod p69_sqrtx; mod p50_powx_n; mod p149_max_points_on_a_line; -mod p70_climbing_stairs; \ No newline at end of file +mod p70_climbing_stairs; +mod p198_house_robber; \ No newline at end of file diff --git a/src/problem/p198_house_robber.rs b/src/problem/p198_house_robber.rs new file mode 100644 index 0000000..c0f3647 --- /dev/null +++ b/src/problem/p198_house_robber.rs @@ -0,0 +1,51 @@ +/** + * [198] House Robber + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn rob(nums: Vec) -> 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])); + } +}