forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution2.java
More file actions
31 lines (24 loc) · 787 Bytes
/
Solution2.java
File metadata and controls
31 lines (24 loc) · 787 Bytes
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
/// Source : https://leetcode.com/problems/house-robber/description/
/// Author : liuyubobobo
/// Time : 2017-11-19
/// Dynamic Programming
/// Time Complexity: O(n)
/// Space Complexity: O(n)
public class Solution2 {
public int rob(int[] nums) {
int n = nums.length;
if(n == 0)
return 0;
// the max profit for robbing nums[i...n)
int[] memo = new int[nums.length];
memo[n - 1] = nums[n - 1];
for(int i = n - 2 ; i >= 0 ; i --)
memo[i] = Math.max(memo[i + 1],
nums[i] + (i + 2 < n ? memo[i + 2] : 0));
return memo[0];
}
public static void main(String[] args) {
int nums[] = {2, 1};
System.out.println((new Solution2()).rob(nums));
}
}