Created
June 4, 2020 03:40
-
-
Save bhaveshmunot1/2848b935e16e6d7c3fc108f6a012b4d2 to your computer and use it in GitHub Desktop.
Leetcode #198: House Robber
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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