shriyanshi24jindal

House Robber II

Mar 28th, 2026
15
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 11.40 KB | None | 0 0
  1. class Solution {
  2. /** Recursion */
  3. public int rob(int[] nums) {
  4. int n = nums.length;
  5.  
  6. return findMaxCost(nums, n);
  7. }
  8.  
  9. public int findMaxCost(int[] nums, int n)
  10. {
  11. // because at index=0, there is a house but it's adjacent so we cannot count the cost
  12. if(n == 0)
  13. return 0;
  14. if(n == 1)
  15. return 1;
  16.  
  17. // pick the house and ignore the adjacents
  18. int pick = nums[n-1] + findMaxCost(nums, n-2);
  19. // do not pick the house and ignore the current house
  20. int notPick = findMaxCost(nums, n-1);
  21.  
  22. return Math.max(pick, notPick);
  23. }
  24.  
  25. /** Memoization
  26.   So, just like I mentioned before, handle two ranges:
  27.   nums[0..n-2] → include first house, exclude last
  28.   nums[1..n-1] → exclude first house, include last
  29.   */
  30. public int rob(int[] nums) {
  31. int n = nums.length;
  32.  
  33. if (n == 1)
  34. return nums[0];
  35.  
  36. // include first house, exclude last
  37. int[] t1 = new int[n+1];
  38. Arrays.fill(t1, -1);
  39. int case1 = findMaxCost(nums, 0, n - 2, t1);
  40.  
  41. // include last house, exclude first
  42. int[] t2 = new int[n+1];
  43. Arrays.fill(t2, -1);
  44. int case2 = findMaxCost(nums, 1, n - 1, t2);
  45.  
  46. return Math.max(case1, case2);
  47. }
  48.  
  49. public int findMaxCost(int[] nums, int start, int end, int[] t)
  50. {
  51. // because at index=0, there is a house but it's adjacent so we cannot count the cost
  52. if(start > end)
  53. return 0;
  54.  
  55. if(t[end] != -1)
  56. return t[end];
  57.  
  58. // pick the house and ignore the adjacents
  59. int pick = nums[end] + findMaxCost(nums, start, end-2, t);
  60. // do not pick the house and ignore the current house
  61. int notPick = findMaxCost(nums, start, end-1, t);
  62.  
  63. t[end] = Math.max(pick, notPick);
  64. return t[end];
  65. }
  66. }
RAW Paste Data Copied