Sunday, February 27, 2022

LeetCode 198. House Robber

 https://leetcode.com/problems/house-robber/



class Solution {
public:
map<int, int> memo;
vector<int> h;
int dp(int i){
// base
if(i == 0)
return h[i];
if(i == 1)
return max(h[0], h[1]);
// use memo
if(memo.find(i) != memo.end())
return memo[i];
// relation
memo[i] = max(dp(i-1), dp(i-2) + h[i]);
return memo[i];
}
int rob(vector<int>& nums) {
h = nums;
int n = nums.size();
return dp(n - 1);
}
};

No comments:

Post a Comment