diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /house_robber.cpp | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'house_robber.cpp')
-rw-r--r-- | house_robber.cpp | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/house_robber.cpp b/house_robber.cpp new file mode 100644 index 0000000..a08aa54 --- /dev/null +++ b/house_robber.cpp @@ -0,0 +1,21 @@ +#include "leetcode.h" + +class Solution { +public: + int rob(vector<int> &nums) { + // space-optimized dynamic programming approach + int prev = 0, prev2 = 0, curr = 0; + for (auto i : nums) { + curr = max(prev, i + prev2); + prev2 = prev; + prev = curr; + } + return curr; + } +}; + +int main() { + Solution obj; + vector<int> nums = {1, 2, 3, 1}; + cout << obj.rob(nums); // expect 4 +} |