213. House Robber II (DP)

 1 class Solution {
 2     public int rob(int[] nums) {
 3         int n = nums.length;
 4         int[] res = new int[n];
 5         if(n == 0) return 0;
 6         if(n == 1) return nums[0];
 7         if(n == 2) return Math.max(nums[0], nums[1]);
 8         res[0] = nums[0];
 9         res[1] = Math.max(nums[0], nums[1]);
10         for(int i = 2; i < n - 1; i++) {
11             for(int j = 0; j < i - 1; j++) {
12                 res[i] = Math.max(res[i - 1], nums[i] + res[i - 2]);
13             }
14         }
15         int[] res1 = new int[n];
16         res1[1] = nums[1];
17         res1[2] = Math.max(nums[1], nums[2]);
18         for(int i = 3; i < n; i++) {
19             for(int j = 0; j < i - 1; j++) {
20                 res1[i] = Math.max(res1[i - 1], nums[i] + res1[i - 2]);
21             }
22         }
23         return Math.max(res[n - 2], res1[n - 1]);
24           
25     }
26 }

猜你喜欢

转载自www.cnblogs.com/goPanama/p/9440419.html
今日推荐