forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution5.java
32 lines (25 loc) · 803 Bytes
/
Solution5.java
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
/// Source : https://leetcode.com/problems/house-robber/description/
/// Author : liuyubobobo
/// Time : 2017-11-19
/// Dynamic Programming
/// Another way to define the states
/// Time Complexity: O(n)
/// Space Complexity: O(n)
public class Solution5 {
public int rob(int[] nums) {
int n = nums.length;
if(n == 0)
return 0;
// the max profit for robbing nums[0...i]
int[] memo = new int[nums.length];
memo[0] = nums[0];
for(int i = 1 ; i < n ; i ++)
memo[i] = Math.max(memo[i - 1],
nums[i] + (i - 2 >= 0 ? memo[i - 2] : 0));
return memo[n-1];
}
public static void main(String[] args) {
int nums[] = {2, 1};
System.out.println((new Solution5()).rob(nums));
}
}