Skip to content

Commit

Permalink
LeetCode #213
Browse files Browse the repository at this point in the history
  • Loading branch information
GGSargsyan authored May 26, 2020
1 parent ca6e0d0 commit b4222cd
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions House Robber II.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution {
public int rob(int[] nums) {

if(nums.length == 0) return 0;
if(nums.length == 1) return nums[0];
if(nums.length == 2) return Math.max(nums[0], nums[1]);

int[] dp1 = new int[nums.length];
int[] dp2 = new int[nums.length];

dp1[0] = nums[0];
dp1[1] = Math.max(nums[0], nums[1]);
dp2[1] = nums[1];

for(int i = 2; i < nums.length; i++){
dp2[i] = Math.max(nums[i] + dp2[i-2], dp2[i-1]);
if(i == nums.length-1) continue;
dp1[i] = Math.max(nums[i] + dp1[i-2], dp1[i-1]);
}

return Math.max(dp2[nums.length-1], dp1[nums.length-2]);
}
}

0 comments on commit b4222cd

Please sign in to comment.