Advertisement
1988coder

198. House Robber

Dec 31st, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. /**
  2.  * Iterative Solution
  3.  *
  4.  * Time Complexity: O(N)
  5.  *
  6.  * Space Complexity: O(1)
  7.  *
  8.  * N = Length of input nums array
  9.  */
  10. class Solution {
  11.     public int rob(int[] nums) {
  12.         if (nums == null || nums.length == 0) {
  13.             return 0;
  14.         }
  15.         if (nums.length == 1) {
  16.             return nums[0];
  17.         }
  18.  
  19.         int previousMax = 0, currentMax = 0;
  20.         for (int num : nums) {
  21.             int temp = currentMax;
  22.             currentMax = Math.max(previousMax + num, currentMax);
  23.             previousMax = temp;
  24.         }
  25.  
  26.         return currentMax;
  27.     }
  28. }
  29.  
  30. /**
  31.  * Recursive Solution. This solution gives time limit exceeded.
  32.  *
  33.  * Time Complexity: O(N)
  34.  *
  35.  * Space Complexity: O(N) - Recursion stack
  36.  *
  37.  * N = Length of the input nums array.
  38.  */
  39. class Solution {
  40.     public int rob(int[] nums) {
  41.         if (nums == null || nums.length == 0) {
  42.             return 0;
  43.         }
  44.         return robHelper(nums, nums.length - 1);
  45.     }
  46.  
  47.     private int robHelper(int[] nums, int i) {
  48.         if (i < 0) {
  49.             return 0;
  50.         }
  51.         return Math.max(robHelper(nums, i - 2) + nums[i], robHelper(nums, i - 1));
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement