Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solved house robber problem #104

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions Pull Here/LeetCode/HouseRobber/Harshitshukla0208.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
int rob(vector<int> &nums)
{
int n = nums.size();
if (n == 0)
return 0;
if (n == 1)
return nums[0];

// Initialize an array to store maximum robbed amount up to each house
vector<int> dp(n, 0);

// Base cases
dp[0] = nums[0];
dp[1] = max(nums[0], nums[1]);

// Fill up the dp array iteratively
for (int i = 2; i < n; i++)
{
// Either rob the current house and add the amount from two houses ago,
// or skip the current house and keep the amount from the previous house.
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);
}

return dp[n - 1];
}
};