Advertisement
1988coder

213. House Robber II

Jan 1st, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | None | 0 0
  1. /**
  2.  * Iterative Solution
  3.  *
  4.  * Refer:
  5.  * https://leetcode.com/problems/house-robber-ii/discuss/59934/Simple-AC-solution-in-Java-in-O(n)-with-explanation/61023
  6.  *
  7.  * Time Complexity: O(N)
  8.  *
  9.  * Space Complexity: O(1)
  10.  *
  11.  * N = Length of the input nums array.
  12.  */
  13. class Solution {
  14.     public int rob(int[] nums) {
  15.         if (nums == null || nums.length == 0) {
  16.             return 0;
  17.         }
  18.         int len = nums.length;
  19.         if (len == 1) {
  20.             return nums[0];
  21.         }
  22.  
  23.         return Math.max(nums[0] + robHelper(nums, 2, len - 2), robHelper(nums, 1, len - 1));
  24.     }
  25.  
  26.     private int robHelper(int[] nums, int left, int right) {
  27.         int previousMax = 0;
  28.         int currentMax = 0;
  29.         for (int i = left; i <= right; i++) {
  30.             int temp = currentMax;
  31.             currentMax = Math.max(currentMax, nums[i] + previousMax);
  32.             previousMax = temp;
  33.         }
  34.         return currentMax;
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement