Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
24 lines (20 loc) · 642 Bytes

File metadata and controls

24 lines (20 loc) · 642 Bytes
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public int rob(int[] num) {
int[][] dp = new int[num.length + 1][2];
for (int i = 1; i <= num.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);
dp[i][1] = num[i - 1] + dp[i - 1][0];
}
return Math.max(dp[num.length][0], dp[num.length][1]);
}
dp[i][1] means we rob the current house and dp[i][0] means we don't,
so it is easy to convert this to O(1) space
public int rob(int[] num) {
int prevNo = 0;
int prevYes = 0;
for (int n : num) {
int temp = prevNo;
prevNo = Math.max(prevNo, prevYes);
prevYes = n + temp;
}
return Math.max(prevNo, prevYes);
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.