-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhouseRobber.cpp
More file actions
66 lines (62 loc) · 1.23 KB
/
Copy pathhouseRobber.cpp
File metadata and controls
66 lines (62 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <bits/stdc++.h>
using namespace std;
// 198. House Robber
class SolutionMemoization
{
int *dp;
public:
int rec(vector<int> &nums, int n)
{
if (n == 0)
return 0;
if (dp[n] != -1)
return dp[n];
if (n == 1)
return dp[n] = nums[n - 1];
return dp[n] = max(nums[n - 1] + rec(nums, n - 2), rec(nums, n - 1));
}
int rob(vector<int> &nums)
{
dp = new int[1e5];
memset(dp, -1, sizeof(int) * 1e5);
return rec(nums, nums.size());
}
};
class SolutionTabulation
{
int *dp;
public:
int rob(vector<int> &nums)
{
int n = nums.size();
dp = new int[1e5]{0};
dp[1] = nums[0];
for (int i = 2; i <= n; i++)
{
dp[i] = max(nums[i - 1] + dp[i - 2], dp[i - 1]);
}
return dp[n];
}
};
class SolutionOptimal
{
public:
int rob(vector<int> &nums)
{
int inc, exc;
inc = nums[0];
exc = 0;
for (int i = 1; i < nums.size(); i++)
{
exc += nums[i];
if (inc < exc)
swap(inc, exc);
else
exc = inc;
}
return max(inc, exc);
}
};
int main()
{
}