1. class Solution {
  2. /** Recursive code */
  3. public int rob(int[] nums) {
  4. int n = nums.length;
  5.  
  6. return findMaxAmount(nums, n);
  7. }
  8.  
  9. public int findMaxAmount(int[] nums, int n)
  10. {
  11. // no houses left
  12. if(n == 0)
  13. return 0;
  14.  
  15. // only one house
  16. if(n == 1)
  17. return nums[0];
  18.  
  19. // pick the house and ignore the adjacents
  20. int pick = nums[n-1] + findMaxAmount(nums, n-2);
  21. // do not pick the house and ignore the current house
  22. int notPick = findMaxAmount(nums, n-1);
  23.  
  24. return Math.max(pick, notPick);
  25. }
  26.  
  27. /** Memoization code */
  28. public int rob(int[] nums) {
  29. int n = nums.length;
  30.  
  31. int[] t = new int[n+1];
  32. Arrays.fill(t, -1);
  33.  
  34. return findMaxAmount(nums, n, t);
  35. }
  36.  
  37. public int findMaxAmount(int[] nums, int n, int[] t)
  38. {
  39. // no houses left
  40. if(n == 0)
  41. return 0;
  42.  
  43. // only one house
  44. if(n == 1)
  45. return nums[0];
  46.  
  47. if(t[n] != -1)
  48. return t[n];
  49.  
  50. // pick the house and ignore the adjacents
  51. int pick = nums[n-1] + findMaxAmount(nums, n-2, t);
  52. // do not pick the house and ignore the current house
  53. int notPick = findMaxAmount(nums, n-1, t);
  54.  
  55. t[n] = Math.max(pick, notPick);
  56. return t[n];
  57. }
  58.  
  59. /** Top-down approach */
  60. public int rob(int[] nums) {
  61. int n = nums.length;
  62.  
  63. int[] t = new int[n+1];
  64.  
  65. // initalise array with base condition
  66. // only one house
  67. t[0] = 0;
  68. // only one house: because at index=0, there is a house which has a cost
  69. t[1] = nums[0];
  70.  
  71. for(int i=2; i<n+1; i++)
  72. {
  73. int pick = nums[i-1] + t[i-2];
  74. int notPick = t[i-1];
  75. t[i] = Math.max(pick, notPick);
  76. }
  77. return t[n];
  78. }
  79. }