Skip to content

Commit efe65fd

Browse files
committed
Added solution of problem 198
1 parent 35467b2 commit efe65fd

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/solutions/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ pub mod s0173_binary_search_tree_iterator;
9999
pub mod s0179_largest_number;
100100
pub mod s0187_repeated_dna_sequences;
101101
pub mod s0189_rotate_array;
102+
pub mod s0198_house_robber;
102103
pub mod s0231_power_of_two;
103104
pub mod s0232_implement_queue_using_stacks;
104105
pub mod s0234_palindrome_linked_list;

src/solutions/s0198_house_robber.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
pub fn rob(nums: Vec<i32>) -> i32 {
2+
if nums.is_empty() {
3+
return 0;
4+
}
5+
if nums.len() == 1 {
6+
return nums[0];
7+
}
8+
9+
let mut prev_prev = nums[0];
10+
let mut prev = nums[0].max(nums[1]);
11+
12+
for i in 2..nums.len() {
13+
let current = prev_prev + nums[i];
14+
prev_prev = prev;
15+
prev = current.max(prev);
16+
}
17+
18+
prev
19+
}
20+
21+
#[cfg(test)]
22+
mod test {
23+
use super::*;
24+
25+
#[test]
26+
fn test_case_1() {
27+
assert_eq!(rob(vec![1, 2, 3, 1]), 4);
28+
}
29+
30+
#[test]
31+
fn test_case_2() {
32+
assert_eq!(rob(vec![2, 7, 9, 3, 1]), 12);
33+
}
34+
}

0 commit comments

Comments
 (0)