cpp: add “198. House Robber”
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
0505779f3f
commit
1c9fea288f
1 changed files with 22 additions and 0 deletions
22
cpp/house-robber.cpp
Normal file
22
cpp/house-robber.cpp
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
class Solution {
|
||||||
|
static int get(const std::vector<int> &nums, int i) {
|
||||||
|
if (i < 0 || i >= static_cast<int>(nums.size())) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return nums[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
public:
|
||||||
|
int rob(std::vector<int> nums) {
|
||||||
|
if (nums.size() == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 1; i < static_cast<int>(nums.size()); ++i) {
|
||||||
|
nums[i] = std::max(nums[i - 1], get(nums, i - 2) + nums[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return nums.back();
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue