Skip to content

Instantly share code, notes, and snippets.

@bhaveshmunot1
Created June 4, 2020 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhaveshmunot1/2848b935e16e6d7c3fc108f6a012b4d2 to your computer and use it in GitHub Desktop.
Save bhaveshmunot1/2848b935e16e6d7c3fc108f6a012b4d2 to your computer and use it in GitHub Desktop.
Leetcode #198: House Robber
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if (n==0) {
return 0;
}
if (n==1) {
return nums[0];
}
if (n==2) {
return max(nums[0], nums[1]);
}
vector<int> dp(n+1, 0);
dp[0] = 0;
dp[1] = nums[0];
dp[2] = max(nums[0], nums[1]);
for (int i=3; i<=n; i++) {
dp[i] = nums[i-1] + max(dp[i-2], dp[i-3]);
}
return max(dp[n], dp[n-1]);
}
};
// Note: Space complexity of this solution can be reduced to O(1) by using 3-4 variables instead of an array/vector.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment