|
| 1 | +// https://leetcode.com/problems/house-robber/ |
| 2 | + |
| 3 | +// ITERATIVE WITH TWO VARIABLES |
| 4 | +class Solution { |
| 5 | + public int rob(int[] nums) { |
| 6 | + if (nums.length == 0) return 0; |
| 7 | + int prev1 = 0; |
| 8 | + int prev2 = 0; |
| 9 | + for (int num : nums) { |
| 10 | + int tmp = prev1; |
| 11 | + prev1 = Math.max(prev1, prev2 + num); |
| 12 | + prev2 = tmp; |
| 13 | + } |
| 14 | + return prev1; |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +// ITERATIVE WITH MEMOIZATION - BOTTOM UP APPROACH |
| 19 | +// class Solution { |
| 20 | +// public int rob(int []nums) { |
| 21 | +// if (nums.length == 0) |
| 22 | +// return 0; |
| 23 | +// int[] memo = new int[nums.length + 1]; |
| 24 | +// memo[0] = 0; |
| 25 | +// memo[1] = nums[0]; |
| 26 | +// for (int i = 1; i < nums.length; i++) { |
| 27 | +// int val = nums[i]; |
| 28 | +// memo[i+1] = Math.max(memo[i], memo[i - 1] + val); |
| 29 | +// } |
| 30 | +// return memo[nums.length]; |
| 31 | +// } |
| 32 | +// } |
| 33 | + |
| 34 | +// RECURSIVE WITH MEMOIZATION - TOP DOWN APPROACH |
| 35 | +// class Solution { |
| 36 | +// int[] memo; |
| 37 | +// public int rob(int[] nums) { |
| 38 | +// memo = new int[nums.length + 1]; |
| 39 | +// Arrays.fill(memo, -1); |
| 40 | +// return rob(nums, nums.length - 1); |
| 41 | +// } |
| 42 | +// public int rob(int[] nums, int i) { |
| 43 | +// if (i < 0) |
| 44 | +// return 0; |
| 45 | +// if (memo[i] >= 0) |
| 46 | +// return memo[i]; |
| 47 | +// memo[i] = Math.max(rob(nums, i - 2) + nums[i], rob(nums, i - 1)); |
| 48 | +// return memo[i]; |
| 49 | +// } |
| 50 | +// } |
| 51 | + |
| 52 | +// RECURSIVE - TOP DOWN APPROACH |
| 53 | +// class Solution { |
| 54 | +// public int rob(int[] nums) { |
| 55 | +// return rob(nums, nums.length - 1); |
| 56 | +// } |
| 57 | +// public int rob(int[] nums, int i) { |
| 58 | +// if (i < 0) |
| 59 | +// return 0; |
| 60 | +// return Math.max(rob(nums, i-2) + nums[i], rob(nums, i-1)); |
| 61 | + |
| 62 | +// } |
| 63 | +// } |
0 commit comments