From 1c9fea288fba66317c6ea3836783802c1ec8196a Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 21 Jan 2024 11:42:11 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=E2=80=9C198.=20House=20Robber?= =?UTF-8?q?=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/house-robber.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 cpp/house-robber.cpp diff --git a/cpp/house-robber.cpp b/cpp/house-robber.cpp new file mode 100644 index 0000000..8b5946c --- /dev/null +++ b/cpp/house-robber.cpp @@ -0,0 +1,22 @@ +class Solution { + static int get(const std::vector &nums, int i) { + if (i < 0 || i >= static_cast(nums.size())) { + return 0; + } + + return nums[i]; + } + + public: + int rob(std::vector nums) { + if (nums.size() == 0) { + return 0; + } + + for (int i = 1; i < static_cast(nums.size()); ++i) { + nums[i] = std::max(nums[i - 1], get(nums, i - 2) + nums[i]); + } + + return nums.back(); + } +};