From d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa Mon Sep 17 00:00:00 2001 From: jack <0x6A73@pm.me> Date: Fri, 14 Jun 2024 13:13:15 -0600 Subject: initial --- house_robber.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 house_robber.cpp (limited to 'house_robber.cpp') 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 &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 nums = {1, 2, 3, 1}; + cout << obj.rob(nums); // expect 4 +} -- cgit v1.2.3