198. House Robber (DP)
1 class Solution { 2 public int rob(int[] nums) { 3 int n = nums.length; 4 int[] res = new int[n + 1]; 5 if(n == 0) return 0; 6 if(n == 1) return nums[0]; 7 if(n == 2) return Math.max(nums[1], nums[0]); 8 res[0] = nums[0]; 9 res[1] = nums[1]; 10 for(int i = 2; i < n; i++) { 11 for(int j = 0; j < i - 1; j++) { 12 res[i] = Math.max(res[i], nums[i] + res[j]); 13 } 14 } 15 int max = 0; 16 for(int i = 0; i < n; i++) { 17 max = Math.max(max, res[i]); 18 } 19 return max; 20 } 21 } 22 23 24 //New 25 class Solution { 26 public int rob(int[] nums) { 27 int n = nums.length; 28 int[] res = new int[n]; 29 if(n == 0) return 0; 30 if(n == 1) return nums[0]; 31 if(n == 2) return Math.max(nums[1], nums[0]); 32 res[0] = nums[0]; 33 res[1] = Math.max(nums[0], nums[1]); 34 for(int i = 2; i < n; i++) { 35 res[i] = Math.max(res[i - 1], nums[i] + res[i - 2]); 36 } 37 return res[n - 1]; 38 } 39 }