|
| 1 | +/* |
| 2 | +
|
| 3 | +198. House Robber |
| 4 | +
|
| 5 | +You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically |
| 6 | +contact the police if two adjacent houses were broken into on the same night. |
| 7 | +Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. |
| 8 | +
|
| 9 | +Example 1: |
| 10 | +Input: nums = [1,2,3,1] |
| 11 | +Output: 4 |
| 12 | +Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). |
| 13 | +Total amount you can rob = 1 + 3 = 4. |
| 14 | +
|
| 15 | +Example 2: |
| 16 | +Input: nums = [2,7,9,3,1] |
| 17 | +Output: 12 |
| 18 | +Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). |
| 19 | +Total amount you can rob = 2 + 9 + 1 = 12. |
| 20 | + |
| 21 | +Constraints: |
| 22 | +
|
| 23 | +1 <= nums.length <= 100 |
| 24 | +0 <= nums[i] <= 400 |
| 25 | +*/ |
| 26 | + |
| 27 | +class Solution { |
| 28 | + static int[] memo = new int[101]; |
| 29 | + public int rob(int[] nums) { |
| 30 | + int n=nums.length; |
| 31 | + //Recursion:: |
| 32 | + //return solveRec(nums,n-1); |
| 33 | + Arrays.fill(memo,-1); |
| 34 | + return solveMemo(nums,n-1); |
| 35 | + |
| 36 | + } |
| 37 | + public static int solveRec(int[] arr,int n){ |
| 38 | + //Base Case :: |
| 39 | + if(n<0) return 0; |
| 40 | + //Choices we have :: |
| 41 | + int rob = arr[n] +solveRec(arr,n-2); |
| 42 | + int notrob =solveRec(arr,n-1); |
| 43 | + |
| 44 | + return memo[n]=Math.max(rob,notrob); |
| 45 | + } |
| 46 | + public static int solveMemo(int[] arr,int n){ |
| 47 | + //Base Case :: |
| 48 | + if(n<0) return 0; |
| 49 | + // precamputed value:: |
| 50 | + if(memo[n]!=-1){ |
| 51 | + return memo[n]; |
| 52 | + } |
| 53 | + //Choices we have :: |
| 54 | + int rob = arr[n] +solveMemo(arr,n-2); |
| 55 | + int notrob =solveMemo(arr,n-1); |
| 56 | + |
| 57 | + return memo[n]=Math.max(rob,notrob); |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments