Skip to content

Commit b464a34

Browse files
authored
Create 213. House Robber II
1 parent 4b3ad12 commit b464a34

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

213. House Robber II

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public int rob(int[] nums) {
3+
if(nums.length==1) return nums[0];
4+
if(nums.length==2) return Math.max(nums[0],nums[1]);
5+
6+
//0th index - n-2 index
7+
int x = helper(0,nums.length-1,nums);
8+
//1st index - n-1 index
9+
int y = helper(1,nums.length,nums);
10+
11+
return Math.max(x,y);
12+
}
13+
14+
private int helper(int start,int end,int[] nums){
15+
int[] dp = new int[end];
16+
dp[start]=nums[start];
17+
dp[start+1] = Math.max(nums[start],nums[start+1]);
18+
for(int index=start+2;index<end;index++){
19+
dp[index] = Math.max(dp[index-2]+nums[index],dp[index-1]);
20+
}
21+
return dp[dp.length-1];
22+
}
23+
}

0 commit comments

Comments
 (0)